I dont understand why the following while loop wont end? The following code just keeps endlessly asking for the user input. Im doing the very first coin flip project and really appreciate any help:
random_choice = random.randint(1,2)
user_input = ""
if random_choice == 1:
random_choice = "Heads"
random_choice = "Tails"
while user_input != "Heads" or user_input != "Tails":
user_input = input("Heads or Tails?")
if user_input == random_choice:
print("Congratulations!", "The result was", random_choice, " and you guess correctly!")
print("Bad luck!", "The result was", random_choice, " and you guessed incorrectly.")
that usually indicates in something is wrong with your loop condition, so i recommend to break down the condition, first start with some invalid input:
while 'invalid' != 'Heads' or 'invalid' != "Tails"
so here i assume the user entered the text:
if we resolve the comparisons:
while true or true:
then resolve the
okay, so the loop condition is true, so the loop will make another iteration
now you do the same for valid input.
I worked through your request on my own and I believe I found the issue (the operator OR).Since one of the subexpressions was always going to be True, then the whole loop is considered True and continues to loop over.
taking an example of “Heads” as user_input:
while “Heads” != “Heads or “Heads” != Tails”:
while False or True
What the AND operator does is require than both booleans return TRUE for the expression to be considered TRUE. In my example one of the booleans is False and therefore the while loop breaks and the code follows on to the next steps.
Am I expressing the steps correctly? I feel like being able to say out loud the steps of the code accurately is half the battle at the beggining (clearly where I was messing up before your suggestion).
Nicely done Teaching yourself these thinking steps is super helpful
You seem to have grasped the problem and solved it
this is so common, it even has a name:
Rubber duck debugging - Wikipedia
This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.