Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...