二十一点“命中或停留”功能中的问题分配变量。循环不正确?

问题描述 投票:1回答:2

我是编程新手。我试图在一个简单的二十一点游戏中创建一个“命中或停留”功能,在try / except / else语句中获取用户输入,该语句也嵌套在while循环检查中,以确保用户输入为“ h”或“ s”。问题在于该变量从未分配给用户输入。这是我所拥有的:

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

该程序总是在最后只返回'else'语句,因此我知道x不能正确接收用户输入。我在做什么错?

python loops input blackjack
2个回答
1
投票
lower是您需要这样调用的函数。您也不需要在while循环中使用else

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

我不确定通过在while循环内使用try-except块来实现什么行为。代码行可能抛出的唯一例外是,如果用户尝试通过按Ctrl + C退出程序。您的代码抓住了这一点,并继续告诉用户输入h或s。这通常不是好行为-最好不要包含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}")

© www.soinside.com 2019 - 2024. All rights reserved.