提问人:Lori C 提问时间:10/28/2023 最后编辑:John KugelmanLori C 更新时间:10/28/2023 访问量:29
为什么我的代码部分无缘无故地只运行了几次?
Why does section of my code only run some times for no reason?
问:
我刚刚开始学习python,并试图编写一个非常简单的Black Jack游戏版本。代码似乎运行良好,但有时它会在打印“Now dealer moves”后停止,没有错误消息或原因。
from random import choices, choice
import inquirer
new_game = True
while new_game:
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
player_hand = choices(cards,k=2)
dealer_hand = choices(cards,k=2)
player_sum = sum(player_hand)
dealer_sum = sum(dealer_hand)
print(player_hand)
print(dealer_hand)
print(f"Your cards are {player_hand} with a score of {player_sum}.")
print(f"The dealer's first card is {dealer_hand[0]}.")
print("\nNow you move first.")
player_end = False
while not player_end:
another_round = input("Type 'y' to deal another card, type 'n' to pass: ").lower()
if another_round == 'y':
player_hand.append(choice(cards))
player_sum = sum(player_hand)
if player_sum > 21 or another_round == 'n':
player_end = True
print(f"Your final hand is {player_hand} with a score of {player_sum}.")
else:
print(f"Your hand is now {player_hand} and current score is {player_sum}.")
if player_sum > 21:
print("Unfortunately you went over. You lose")
else:
print('\nNow dealer moves.')
dealer_end = False
while not dealer_end:
if dealer_sum < 17:
dealer_hand.append(choice(cards))
dealer_sum = sum(player_hand)
else:
dealer_end = True
print(f"The dealer's final hand is {dealer_hand} with a score of {dealer_sum}.")
if player_sum > dealer_sum:
print("You won!")
elif player_sum == dealer_sum:
print("It's a draw")
else:
print("You lose.")
another_game = input("\nDo you like to start a new game? Type 'y' to start and 'n' to exit. ")
if another_game == 'n':
new_game = False
else:
print("\n")
我尝试过多次运行它,但仍然没有看到它何时停止工作的明确模式。
谁能帮我发现错误?
答:
0赞
John Kugelman
10/28/2023
#1
while not dealer_end:
if dealer_sum < 17:
dealer_hand.append(choice(cards))
dealer_sum = sum(player_hand)
else:
dealer_end = True
它正在添加卡片,但计算 的总和是不变的。循环永无止境。dealer_hand
player_hand
评论