Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

Turning this code into a python function

This is my code:

name1 = input(userQuestions[0]).lower()
while name1 == "" or not name1.replace(' ','').isalpha():
    name1 = input(userQuestions[0]).lower()

The 'userQuestions[ ]' are:

userQuestions = (
    "Give me name 1?
",
    "Give me name 2?
",
    "Give me name 3?
",
    )

To use my validation on all 3 questions, how do I put this into a function to make it more efficient instead of repeating a similar statement x3?
The only thing that should change in the function is the name (eg. 'name1' to 'name2', 'name3'), and the userQuestions[ ] (eg. userQuestions[0], ...[1], ...[2]).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I am understanding you correctly then I think this is what you are looking for. This loops through your userQuestions tuple and calls the function get_user() which returns the new username and adds it to the list users

def get_user(userQuestion):
    name1 = input(userQuestion).lower()
    while name1 == "" or not name1.replace(' ','').isalpha():
        name1 = input(userQuestion).lower()
    return name1

userQuestions = (
    "Give me name 1?
",
    "Give me name 2?
",
    "Give me name 3?
",
    )
users = []

for i in userQuestions:
    users.append(get_user(i))

print(users)

You could change this up a little since the only thing you are changing in the questions is the number you could put the string in the function and only pass the number in like so,

def get_user(x):
    name1 = input('Give me name ' + x + '
').lower()
    while name1 == "" or not name1.replace(' ','').isalpha():
        name1 = input('Give me name ' + x + '
').lower()
    return name1

users = []

for i in range(3):
    users.append(get_user(str(i+1)))

print(users)

This way it is easier to scale to any number of users. Say if you have 20 users all you have to do is change the range to 20 instead of adding 17 more lines to you userQuestions tuple.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...