Ember Ember - 4 months ago 9
Bash Question

Python not responding in loop

Here is my code:

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()


now, that works fine, if I happen to get the unlucky number.

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


This is the part where it stops responding entirely. I am running it in a bash interactive shell (Terminal, on osx). It just ends up blank.

I am new to programming in python, I spent most of my time as a web developer. If you are going to down-vote, please say why in the comments.

Thanks in advance.

Answer

In python3, the input function returns a string. You're comparing this string value to a random int value. This will always evaluate to False. Since you only ask for user input once, before the loop, the user never gets a chance to choose a new number and the loop keeps comparing a random number to a string forever.


I'm not sure what exactly your code is supposed to do, but you probably wanted to do something like this:

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.")

See also: Asking the user for input until they give a valid response

Comments