PhantomDiclonius
PhantomDiclonius

Reputation: 149

My Python code is not outputting anything?

I'm currently trying to teach myself Python with the Python Crash Course book by Eric Matthes and I seem to be having difficulties with excercise 5-9 regarding using if tests to test empty lists.

Here is the question:

5-9. No Users: Add an if test to hello_admin.py to make sure the list of users is not empty.

• If the list is empty, print the message We need to find some users!

• Remove all of the usernames from your list, and make sure the correct message is printed.

Here is my code from hello_admin.py:

usernames = ['admin', 'user_1', 'user_2', 'user_3', 'user_4']

for username in usernames:

    if username is 'admin':
        print("Hello admin, would you like to see a status report?")
    else:
        print("Hello " + username + ", thank you for logging in again.")

Now here is my code for 5-9 which is not outputting anything:

usernames = []

for username in usernames:

    if username is 'admin':
        print("Hello admin, would you like to see a status report?")
    else:
        print("Hello " + username + ", thank you for logging in again.")
    if usernames:
        print("Hello " + username + ", thank you for logging in again.")
    else:
        print("We need to find some users!")

Does anyone having any feedback for why my code is not outputting: "We need to find some users!" Thank you for your time. :)

Upvotes: 1

Views: 551

Answers (2)

DeA
DeA

Reputation: 1918

The first if-else should come inside the the for loop. The second if else block should come outside.

usernames = []

for username in usernames:

    if username is 'admin':
        print("Hey admin")
    else:
        print("Hello " + username + ", thanks!")

if usernames:
    print("Hello " + username + ", thanks again.")
else:
    print("Find some users!")

Upvotes: 0

Chuck
Chuck

Reputation: 874

It's not outputting anything since your if and else blocks are inside the for loop which iterates over usernames. Since usernames is an empty list, it's not iterating over anything, hence not reaching any of those conditional blocks.

You might want to put instead:

usernames = []
for username in usernames:
    if username is 'admin':
        print("Hello admin, would you like to see a status report?")
    else:
        print("Hello " + username + ", thank you for logging in again.")

if usernames:
    print("Hello " + username + ", thank you for logging in again.")
else:
    print("We need to find some users!")

That will print the last username in the usernames list twice, though.

Upvotes: 2

Related Questions