简体   繁体   English

当按下回车键时循环不会中断

[英]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. 下面的程序是一个使用Python3编写的随机库的骰子模拟器。 It randomly selects 1 digit out of 6 numbers that are there on a dice. 它从骰子上的6个数字中随机选择1个数字。

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. 问题:当我在执行时按Enter(返回)键时,程序使用的是'y'大小写,并给出一个随机值,而不是结束(中断循环)程序。 Why is that? 这是为什么?

When you press return , the input is an empty string. 当您按return ,输入为空字符串。 This is found in any string at all, so your check is still True : you did a character check on a string. 可以在任何字符串中找到它,因此您的检查仍然是True :您对字符串进行了字符检查。 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. 这将捕获大写或小写的Y ,但仍无法以空字符串终止。

As others have suggested, use a different check, so you're looking for a whole_string match: 正如其他人建议的那样,请使用其他检查,因此您正在寻找一个Whole_string匹配项:

if pipe in ['y', 'Y']:

将if条件更改为

if pipe is 'y':

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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