Python的环路

Python的环路

问题描述:

这里没有响应是我的代码:Python的环路

from random import randint 
doorNum = randint(1, 3) 
doorInp = input("Please Enter A Door Number Between 1 and 3: ") 
x = 1 
while (x == 1) : 
    if(doorNum == doorInp) : 
     print("You opened the wrong door and died.") 
     exit() 
现在

,如果我碰巧得到了不吉利的数字工作正常。

else : 
    print("You entered a room.") 
    doorNum = randint(1, 3) 

这是完全停止响应的部分。我在bash交互式shell(Terminal,在osx上)运行它。它只是空白。

我是Python新手,我花了大部分时间作为Web开发人员。

UPDATE:

感谢@rawing,我还不能给予好评(新手),这样就会把它放在这里。

+1

为什么'while(x == 1)'循环? –

+0

这是python2还是python3? –

+0

@Rawing python3我想。 – Ember

在python3中,input函数返回一个字符串。您将此字符串的值与随机的int值进行比较。这将始终评估为False。由于您只要求用户输入一次,在循环之前,用户永远不会有机会选择新的号码,并且循环会不断地将一个随机数与一个字符串进行比较。


我不知道究竟你的代码是应该做的,但你可能想要做这样的事情:

from random import randint 

while True: 
    doorNum = randint(1, 3) 
    doorInp = int(input("Please Enter A Door Number Between 1 and 3: ")) 

    if(doorNum == doorInp) : 
     print("You opened the wrong door and died.") 
     break 

    print("You entered a room.") 

参见:Asking the user for input until they give a valid response

如果您正在使用python3,然后input返回一个字符串,并将一个字符串与一个int进行比较总是为false,因此您的exit()函数永远不能运行。

您的doorInp变量是一个字符串类型,这是因为您将它与if语句中的整数进行比较而引发该问题。您可以通过在输入行后添加诸如print(type(doorInp))之类的内容来轻松进行检查。 要修复它,只需将输入语句括在int()中:doorInp = int(input("...."))