Skip to content Skip to sidebar Skip to footer

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[

Solution 1:

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?\n",
    "Give me name 2?\n",
    "Give me name 3?\n",
    )
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 + '\n').lower()
    while name1 == "" or not name1.replace(' ','').isalpha():
        name1 = input('Give me name ' + x + '\n').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.


Post a Comment for "Turning This Code Into A Python Function"