Python Forum

Full Version: Problem with an IF statement
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Hi Guys,

Still fairly new here, wondering why this loop is not working.. im trying to create a simple coin flip game. I know there is plenty of resource online for this and so many simple ways of doing this program however I'd like to finish up on what i have created without looking at the other ways. I think you'll see what i means when you see the code.

import random

coin = ('heads','tails')
user_choice = input("Heads or Tails? ")
game = 0
while True:
    try:
        if user_choice.lower() in ("heads","Heads", "HEADS"):
            print("You have selected: Heads ")
            break
        elif user_choice.lower() in ("Tails","tails","TAILS"):
            print("You have selected: Tails ")
            break
    except ValueError:
            print("You can only choose Heads or Tails")



while True:
    print ("Coin has landed on: " ,random.choice(coin))
    if coin == user_choice:
        print("winner")
        game =+ 1
        print(game)
    else:
        print("You lose")
        break
In my head this should work perfectly... however when i execute the code it says i lose everytime... even if i win!?

Any help would be much appreciated.

Sorry for the nooby questions.

Thank you!
Ryan :)
there are number of problems in your logic.
so, first - your question
on line 21 you compare coin, i.e. a tuple with 2 elements with a string. They never be equal. you want to compare what the outcome of the coin flip is. i.e. you need to assign the value returned from random.choice(coin)) to a name and then use that name in the print function on line 20 and in the if condition on line 21.

Then, even in this case, it may still not work if user used capital letters in his choice, e.g. if they enter Heads. You never convert user_choice to lowercase (and keep it converted). You user lower() method on lines 8 and 11, but again it's not stored back into user_choice or other name. the easiest way forward is to just apply .lower() on the result of the input() function, e.g.
user_choice = input("Heads or Tails? ").lower()
In this case you don't need to apply it again on lines8 and 11
Because you apply .lower() on lines 8 and 11 it doesn't make sense to have a tuple, e.g. ("heads","Heads", "HEADS"). Obviously lowercase cannot be Heads or HEADS. user_choice.lower() == 'heads' would be enough (assuming you didn't apply .lower() on the input function as shown above). you can use in to allow user to enter one-letter choice:
        if user_choice.lower() in ("heads","h"):
            print("You have selected: Heads ")
            user_choice = 'heads' # in case user selected 'h', we need the whole word
            break
Next problem is the use of try/except - you cannot get ValueError, because you actually not doing anything that can raise ValueError in the first place. You want to use if/elif/else block and remove the try/except. And you want to ask the user inside the while loop until you get heads or tail from them

Finally, the second while loop - given that you fix all of the above, it will ask for your choice once and then it will loop till your selection is wrong. e.g. it can flip three times in a row heads and you will win 3 games, but if you are incorrect it will break out immediately. Is that the logic you want to implement? Don't you want to ask user before every coin flip? Don't you want to flip the coin certain number of times and then print how many times user was correct?
(Jan-30-2020, 11:03 AM)buran Wrote: [ -> ]there are number of problems in your logic.
so, first - your question
on line 21 you compare coin, i.e. a tuple with 2 elements with a string. They never be equal. you want to compare what the outcome of the coin flip is. i.e. you need to assign the value returned from random.choice(coin)) to a name and then use that name in the print function on line 20 and in the if condition on line 21.

Then, even in this case, it may still not work if user used capital letters in his choice, e.g. if they enter Heads. You never convert user_choice to lowercase (and keep it converted). You user lower() method on lines 8 and 11, but again it's not stored back into user_choice or other name. the easiest way forward is to just apply .lower() on the result of the input() function, e.g.
user_choice = input("Heads or Tails? ").lower()
In this case you don't need to apply it again on lines8 and 11
Because you apply .lower() on lines 8 and 11 it doesn't make sense to have a tuple, e.g. ("heads","Heads", "HEADS"). Obviously lowercase cannot be Heads or HEADS. user_choice.lower() == 'heads' would be enough (assuming you didn't apply .lower() on the input function as shown above). you can use in to allow user to enter one-letter choice:
        if user_choice.lower() in ("heads","h"):
            print("You have selected: Heads ")
            user_choice = 'heads' # in case user selected 'h', we need the whole word
            break
Next problem is the use of try/except - you cannot get ValueError, because you actually not doing anything that can raise ValueError in the first place. You want to use if/elif/else block and remove the try/except. And you want to ask the user inside the while loop until you get heads or tail from them

Finally, the second while loop - given that you fix all of the above, it will ask for your choice once and then it will loop till your selection is wrong. e.g. it can flip three times in a row heads and you will win 3 games, but if you are incorrect it will break out immediately. Is that the logic you want to implement? Don't you want to ask user before every coin flip? Don't you want to flip the coin certain number of times and then print how many times user was correct?

Thank you for this response, very much the kind of response i was after. I will make some changes as advised and see where i get!

:)
Note that you can simplify the user_choice verification
if user_choice in coins: # assuming you applied lower() on input function
    print(f'you selected {user_choice}')
else:
    print('Please select heads or tails')
(Jan-30-2020, 11:17 AM)buran Wrote: [ -> ]Note that you can simplify the user_choice verification
if user_choice in coins: # assuming you applied lower() on input function
    print(f'you selected {user_choice}')
else:
    print('Please select heads or tails')

Thanks man,

Please see below:

import random

coin = ('heads','tails')
user_choice = input("Heads or Tails? ").lower()
game = 0
while True:
    try:
        if user_choice in ("heads","h"):
            print("You have selected: {}".format(user_choice))
            user_choice = 'heads'
            break
        elif user_choice in ("tails","t"):
            print("You have selected: {}".format(user_choice))
            user_choice = 'tails'
            break
        else:
            print("You can only choose Heads or Tails")
            continue


        print ("Coin has landed on: " ,random.choice(coin))
        if coin == user_choice:
            print("winner")
            game =+ 1
            print(game)
            break
        else:
            print("You lose")
            continue
This is currently my code now. Looks a lot nicer. I am trying to test it to see how it runs and then i can try and fix/improve on it. Im getting an EOF error now...

Any ideas?

Its really frustrating!

Thanks for your help.
you have a try without except- just remove it
(Jan-30-2020, 12:08 PM)buran Wrote: [ -> ]you have a try without except- just remove it

Doh! Makes sense

mport random

coin = ('heads','tails')
game = 0
while True:
        user_choice = input("Heads or Tails? ").lower()
        if user_choice in ("heads","h"):
            print("You have selected: {}".format(user_choice))
            user_choice = 'heads'
            #break
        elif user_choice in ("tails","t"):
            print("You have selected: {}".format(user_choice))
            user_choice = 'tails'
            #break
        else:
            print("You can only choose Heads or Tails")
            continue

        print ("Coin has landed on: " ,random.choice(coin))
        
        if coin == user_choice:
            print("winner")
            game =+ 1
            print(game)
        else:
            print("You lose")
            continue
My code has now been modified as suggested.

I still have a problem with the first question i raised. I understand your answer to me and how i am comparing the coin flip result to a tuple and how it will never match.

I have now changed the value of the coin to match either heads or tails. Why is it still coming back as a loss when i win?

Thanks,
Ryan Huh
(Jan-30-2020, 01:16 PM)Ryan_Todd Wrote: [ -> ]I have now changed the value of the coin to match either heads or tails.
no, you still compare coin (i.e. tuple) with use_choice (i.e. string):
if coin == user_choice:
as I advise you in my first answer - assign the result of random.choice(coin)) to a name and use it in the code (lines 19 and 21)
(Jan-30-2020, 01:34 PM)buran Wrote: [ -> ]
(Jan-30-2020, 01:16 PM)Ryan_Todd Wrote: [ -> ]I have now changed the value of the coin to match either heads or tails.
no, you still compare coin (i.e. tuple) with use_choice (i.e. string):
if coin == user_choice:
as I advise you in my first answer - assign the result of random.choice(coin)) to a name and use it in the code (lines 19 and 21)


Thanks for your patience...

How do i assign the result of a random variable without knowing what it could be?

Thanks,
Ryan
How do you assign the value returned from input when you don't know what it will be?
I can write the code, but it will be more beneficial for you if you get it done yourself.
Pages: 1 2