While loop not ending

Hi guys,

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:

import random

def coin_flip():

    random_choice = random.randint(1,2)

    user_input = ""

    if random_choice == 1:

        random_choice = "Heads"

    else:

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

    else:

        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: invalid

if we resolve the comparisons:

while true or true:

then resolve the or:

while true:

okay, so the loop condition is true, so the loop will make another iteration

now you do the same for valid input.

1 Like

Thanks stetim94,

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

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

1 Like

Nicely done :slight_smile: Teaching yourself these thinking steps is super helpful :slight_smile:

You seem to have grasped the problem and solved it :smiley:

this is so common, it even has a name:

https://en.wikipedia.org/wiki/Rubber_duck_debugging

1 Like

This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.