Issue assigning variable in blackjack 'hit or stay' function. Looping incorrectly?

Viewed 51

I'm new to programming. I'm trying to create a 'hit or stay' function in a simple blackjack game taking user input in a try/except/else statement, which is also nested inside a while loop checking to make sure the user input is either 'h' or 's'. The problem is that the variable is never assigned to the user input. Here's what I have:

def hit_or_stay(deck,hand):
    global playing
    x = '' # just holds input for hit/stay

    while x !='h' and x !='s':
        try:
            x = input('HIT or STAY? (h/s): ').lower
        except:
            print("Please enter h to hit or s to stay." )
        else:
            break
    if x == 'h':
        print("You have chosen to hit.")
        hit(deck,hand)
    elif x == 's':
        print("You have chosen to stay.")
        playing = False
    else:
        print(f"x equals {x}")

The program always just returns the 'else' statement at the end, so I know x is not properly taking the user input. What am I doing wrong?

1 Answers

lower is a function you need to call like so. You also don't need the else in the while loop.

def hit_or_stay(deck,hand):
    global playing
    x = '' # just holds input for hit/stay

    while x !='h' and x !='s':
        try:
            x = input('HIT or STAY? (h/s): ').lower()
        except:
            print("Please enter h to hit or s to stay." )
    if x == 'h':
        print("You have chosen to hit.")
        hit(deck,hand)
    elif x == 's':
        print("You have chosen to stay.")
        playing = False
    else:
        print(f"x equals {x}")

I'm not sure what behaviour you want by having the try-except block inside the while loop. The only exception that line of code is likely to throw is if a user attempts to quit the program by pressing Ctrl+C. Your code catches this and continues to tell the user to enter h or s. This is not typically good behaviour - better to not include the try-except.

def hit_or_stay(deck,hand):
    global playing
    x = '' # just holds input for hit/stay

    while x !='h' and x !='s':
        x = input('HIT or STAY? (h/s): ').lower()
    if x == 'h':
        print("You have chosen to hit.")
        hit(deck,hand)
    elif x == 's':
        print("You have chosen to stay.")
        playing = False
    else:
        print(f"x equals {x}")
Related