在 blackjack 'hit or stay' 函数中分配变量问题。循环不正确?
Issue assigning variable in blackjack 'hit or stay' function. Looping incorrectly?
我是编程新手。我正在尝试在一个简单的二十一点游戏中创建一个 'hit or stay' 函数,在 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}")
程序最后总是 returns 'else' 语句,所以我知道 x 没有正确接受用户输入。我做错了什么?
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}")
我不确定将 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}")
我是编程新手。我正在尝试在一个简单的二十一点游戏中创建一个 'hit or stay' 函数,在 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}")
程序最后总是 returns 'else' 语句,所以我知道 x 没有正确接受用户输入。我做错了什么?
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}")
我不确定将 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}")