gpt4 book ai didi

python - 在二十一点 'hit or stay' 函数中分配变量的问题。循环不正确?

转载 作者:行者123 更新时间:2023-12-04 09:45:56 34 4
gpt4 key购买 nike

我是编程新手。我试图在一个简单的二十一点游戏中创建一个“命中或停留”函数,在 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 没有正确接受用户输入。我究竟做错了什么?

最佳答案

lower是您需要像这样调用的函数。您也不需要 else在while循环中。

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

我不确定您想要什么行为 try-except在 while 循环内阻塞。该行代码可能抛出的唯一异常是用户尝试按 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}")

关于python - 在二十一点 'hit or stay' 函数中分配变量的问题。循环不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62114703/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com