Home > Blockchain >  My input is always true and infinite loop
My input is always true and infinite loop

Time:06-08

I can't seem to understand while my code will run no matter what is entered. I have it set to 'yes' gives you a certain output and anything like 'no' should give you something else. It also runs on an infinite loop which I'm sure I can fix later somehow. Thanks for any help I am sorry for the probably dumb question.

print("the test game")
choice = input("do you want to play? Yes or No?")

choice = "Yes"
while choice == "Yes":
    print("No you don't..")
else:
    print("Yes you do..")

CodePudding user response:

So I was looking at your code and I tried to run it on my device and well, an observation to be mentioned first is, that you have defined a variable choice as input first and then given it "yes" as the value later.

The reason the loops continues to work is that, while loop will work until the input it gets remains the same and as you could see that te input of choice is set to "yes", it is not a one time use value but it will run the loop infinitely. The while loop requires the value which has been given already so it doesn't need an input from the user. That's that with your infinite loop issue.

And I think, you want the answer to the question why your code doesn't work, well that is also because of that variable choice which is nuisance at this point. It discards the user input from above. So well, the choice in the while loop will also work, when you remove

choice = "yes"

because this is the major statement resenting the ideal flow of the program.


I hope I could be of any help, if you need any help do comment as ask me!

CodePudding user response:

whatever we received from the user, we convert to lower case hence we can compare with lower case yes/no.

as @shadowRanger mentioned, you have explicitly declare choice after getting the user input that's why whatever user gives it will be changed to yes and you are stucked in the for loop.

val = input("do you want to play? ")
print(val)
if val.lower() == "yes":
    print("test : yes is given")
elif val.lower() == "no":
    print("test : no is given")
else:
    print("sorry wrong command")

if you are using python 2.x then use the raw_input function

Reference https://www.geeksforgeeks.org/taking-input-in-python/

CodePudding user response:

Taking input from user choice = input("do you want to play? Yes or No?"), you can declare variable choice = "Yes". No matter what you entered, Python compiles code line by line, user can input "No", choice variable stores "No" but after it executes the next line it can replace "No" and your new value is "Yes" because of choice = "Yes" this line of code. Simply remove this line choice = "Yes".

  • Related