Home > database >  Why does my code skip all the ifs and go straight to the else statement even tho the requirements of
Why does my code skip all the ifs and go straight to the else statement even tho the requirements of

Time:06-19

import random 
                player=""
                com=""
                start = input("Press enter to start")
                def bj():   
                    com = random.choice([2,3,4,5,6,7,8,9])
                    print(com)
                    player = input("Hit/Stand/Forfeit: ").lower()
                    
                    print(player)
                
                def stand():
                    if player_value > com and player_value != 22:
                        print("You win")

I already wrote player != "forfeit". But even when player is not "forfeit", it still runs

while player != 22 or player != "forfeit":
         bj()

    

Here are the conditions. Even if you type "hit"/"forfeit"/"stand", it goes straight to else.

if player == "hit":
            player_value = random.choice([2,3,4,5,6,7,8,9])
         elif player == "stand" or player == 22:
            stand()
            break   
         elif player == "forfeit":
              break
         else:
             print("Invalid. Try again")   
             print("----------------------")

CodePudding user response:

A variable cannot be two values at once. Since your condition is checking that it's not equal to two different values, one or the other piece is guaranteed to be true. You probably wanted:

player != 22 and player != "forfeit"
#            ^^^

CodePudding user response:

I hope this helps.

import random


def stand():
    print('stand')


player = 'hit' # Test different player values.
while True:
    if player == "hit":
        player_value = random.choice([2, 3, 4, 5, 6, 7, 8, 9])
        break # This break is required. Was not in the example code.
    elif player == "stand" or player == 22:
        stand()
        break
    elif player == "forfeit":
        break
    else:
        print("Invalid. Try again")
        print("----------------------")
  • Related