简体   繁体   中英

While Loop doesn't break when enter (return) key is pressed

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?

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']:

将if条件更改为

if pipe is 'y':

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM