Reputation: 37
empty_Carton = ''
print("Is the milk carton in the fridge empty? y/n")
input(empty_Carton)
while (empty_Carton != 'y') or (empty_Carton != 'n'):
if empty_Carton == 'y':
"""Branch here"""
elif empty_Carton == 'n':
"""Branch here"""
else:
print(empty_Carton + " is not a valid input. Type: 'y' or 'n'")
When I run this code it enters and infinite loop stuck on the 'else' condition when entering a correct input of 'y'
I tried moving the code around and changing the comparison operator but it still ends up in an infinite loop.
Upvotes: 0
Views: 632
Reputation: 3970
You have entered the input only once before while loop. Therefore it will run infinite times. Write a function instead and call that function in your else
condition or just use a break
statement.
empty_Carton = ""
print("Is the milk carton in the fridge empty? y/n")
while (empty_Carton != 'y') or (empty_Carton != 'n'):
if empty_Carton == 'y':
"""Branch here"""
elif empty_Carton == 'n':
"""Branch here"""
else:
print(empty_Carton + " is not a valid input. Type: 'y' or 'n'")
break
Upvotes: -1
Reputation: 15652
The first issue is that empty_Carton
never gets defined to be anything other than ""
, you can fix this with:
empty_Carton = input("Is the milk carton in the fridge empty? y/n")
Note that the input
function takes a string to print and returns the string entered by the user.
The next issue is that your input
call is only made once (above the while
loop), so the value of empty_Carton
never gets updated and your loop runs forever. Really empty_Carton
's value should only get set at the top of the loop so that the loop will execute at least once, but will continue to execute until a valid value is entered.
Finally, since empty_Carton
can never be both 'y'
and 'n'
, empty_Carton
must always be not equal to at least one of those options, so your while
condition is always True
. You can fix this by replacing the or
with an and
, or with:
while empty_Carton not in ('y', 'n'):
# do stuff
Putting this all together, we get something like:
empty_Carton = ''
while empty_Carton not in ('y', 'n'):
empty_Carton = input("Is the milk carton in the fridge empty? y/n")
if empty_Carton == 'y':
print('y')
elif empty_Carton == 'n':
print('n')
Upvotes: 2