Python – Having issues getting my function to loop through items in my list

Question:

Can someone help me and explain where I am going wrong with this code please?

I am working through the Python Crash Course and have tried to modify a program that greets users from a list.The issues is the output only ever works for the first name in the list.


#function that should greet every user in the list of users.
def greet_users(names):
    for name in names:
        msg=print(f"nHello {name}")
        return(msg)

#How the user will quit the while loop.
print("Enter Q to exit")
total_users=[] 
#while loop to populate the list.
while True:
    user = input("Enter a user ")
    if user =="Q":
        break
    else:
        total_users.append(user)
        
greet_users(total_users)

Just for my piece of mind, is someone able to explain where this is going wrong?
I have a feeling it is the function itself but when I read it, I feel the for loop is the issues but at the same time, it works in the book!

Thanks!

I tried changing the while loop to see if it was not populating the list. When entering three names and just printing the list, it does in fact fill it in.

Which leads me to think the problem is the function but I am unsure on what part. The for loop was my initial thought however the book uses the exact same loop and it works.

Asked By: Benjamin Townshend

||

Answers:

The return statement inside of your for loop causes the function to exit.

Also, the print function always returns None, so you don’t need to save it to a variable.

def greet_users(names):
    for name in names:
        print(f"nHello {name}")
Answered By: James

The issue with the code is with the return statement inside the greet_users function. The return statement is causing the function to exit after the first iteration of the for loop, which is why it only works for the first name in the list.

To fix the issue, remove the return statement and simply print the message inside the for loop:

def greet_users(names):
    for name in names:
        print(f"nHello {name}")

With this modification, the function will print a greeting message for every name in the list, instead of exiting after the first iteration.

Answered By: sqrmelon
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.