Reputation: 303
The program below is a dice simulator using the random library written in Python3. It randomly selects 1 digit out of 6 numbers that are there on a dice.
import random
while True:
pipe = input("Type y to roll the dice ")
if pipe in ('y'):
numbers = [1,2,3,4,5,6]
x = random.choice(numbers)
print (x)
else:
print ("GoodBye")
break
Problem: When I press the enter (return) key upon execution the program is using the 'y' case and giving out a random value and not ending (breaking the loop) the program. Why is that?
Upvotes: 0
Views: 130
Reputation: 77847
When you press return
, the input is an empty string. This is found in any string at all, so your check is still True
: you did a character check on a string. You might have extended this with
if pipe in "Yy":
This would catch either upper- or lower-case Y
, but still fails to terminate on an empty string.
As others have suggested, use a different check, so you're looking for a whole_string match:
if pipe in ['y', 'Y']:
Upvotes: 1