usernames = []
for username in usernames:
if username == 'admin':
print("Hello admin, would you like a status report?")
if username != 'admin':
print("Hello " + username + ", thank you for logging in again!")
else:
print("We need more users!")
Error:
what is expected
Output:
We need more users!
With an empty list there is nothing to loop
Supposedly with the list being empty, the last comment should execute. Atleast according to the book, Python Crash Course.
a for loop iterates over items, if there are no items to iterate, nothing will happen
for username in usernames:
username
gets each item from
usernames
if there are no items to get it won't be assigned as anything.
You would need an if statement that is outside of the loop that checks for an empty list.
usernames = []
for username in usernames:
if username == 'admin':
print("Hello admin, would you like a status report?")
if username != 'admin':
print("Hello " + username + ", thank you for logging in again!")
else:
print("We need more users!")
It has to be
else
related to the
for
loop, not as part of
if
.`
else
part of the loop is executed if no
break
statement is hit inside the loop.
Note that it doesn't make sense to iterate over users in the list - if the list is not empty it will print something for every user in the list and again will print the else part (because there is no break inside the loop)
(Jun-14-2020, 04:58 PM)buran Wrote: [ -> ]usernames = []
for username in usernames:
if username == 'admin':
print("Hello admin, would you like a status report?")
if username != 'admin':
print("Hello " + username + ", thank you for logging in again!")
else:
print("We need more users!")
It has to be else
related to the for
loop, not as part of if
.`
else
part of the loop is executed if no break
statement is hit inside the loop.
Note that it doesn't make sense to iterate over users in the list - if the list is not empty it will print something for every user in the list and again will print the else part (because there is no break inside the loop)
Nice!! This one stumped me!!
This gives he same results.
usernames = []
for username in usernames:
if username == 'admin':
print("Hello admin, would you like a status report?")
if username != 'admin':
print("Hello " + username + ", thank you for logging in again!")
print("We need more users!")
It doesn't make sense to use for / else unless you also use break.
(Dec-10-2023, 02:59 AM)deanhystad Wrote: [ -> ]It doesn't make sense to use for / else unless you also use break.
A lot of things don't make sense in this poor example from a book :-) e.g. why 2 separate if, and not if/else, string concatenation, etc.