为什么 "break" 不停止 while 循环 (Python)

why doesn't "break" stop a while loop (Python)

所以我在做一个 21 点程序。一切正常,直到我得到这个:

Your cards:  [2, 4] 
Total:  6
Chose your next move: stand

Dealer's cards:  [5]
Your cards:  [2, 4, 10] 
Total:  16
Chose your next move: stand


//////////////////////////
Dealer's cards:  [5]
Your cards:  [2, 4, 10, 10] 
Total:  26 
//////////////////////////

循环应该在 move == stand 时中断 我认为这是 break 函数,但很有可能我搞砸了其他事情。 这是我认为搞砸了的代码:

while player_cards_total < 21:
  player_cards_total = sum(player_cards)
  dealer_cards_total = sum(dealer_cards)
  if player_cards_total > 20:
    print('\n\n//////////////////////////\nDealer\'s cards: ', dealer_cards)
    print('Your cards: ', player_cards,'\nTotal: ', player_cards_total, '\n//////////////////////////')
    print('\nBUST\n')
    break
  move = get_move()
  
  if move == 'hit':
    player_cards.append(get_card())
  else:
    break

while 循环是一个单独的循环,而不是内部循环

这是完整的代码

import time



Ace = 11
Jack = 10
Queen = 10
King = 10


cards = [Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King]



Ace_21 = False
player_bal = 0
dealer_bal = 0
player_cards = []
dealer_cards = []
player_cards_total = 0
dealer_cards_total = 0
card = ''
move = ''
moves = 0

def get_card():
  return(int(cards[random.randrange(1, 13)]))


dealer_cards =  [get_card(),]
player_cards = [get_card(), get_card()]
player_cards_total = sum(player_cards)


def get_move():
  
  if moves == 0:
    print('\nDealer\'s cards: ', dealer_cards)
    print('Your cards: ', player_cards,'\nTotal: ', player_cards_total)
  move = input('Chose your next move: ')
  if move == 'h' or 'Hit':
    move = 'hit'
  elif move == 's' or 'Stand':
    move = 'stand'
  return(move)



while player_cards_total < 21:
  player_cards_total = sum(player_cards)
  dealer_cards_total = sum(dealer_cards)
  if player_cards_total > 20:
    print('\n\n//////////////////////////\nDealer\'s cards: ', dealer_cards)
    print('Your cards: ', player_cards,'\nTotal: ', player_cards_total, '\n//////////////////////////')
    print('\nBUST\n')
    break
  move = get_move()
  
  if move == 'hit':
    player_cards.append(get_card())
  else:
    break


if player_cards_total > 21:
   print('You lose!!!')
elif player_cards_total == 21:
  print('Great job, you win')
else:
  print('DEALER\'S TURN')
  while dealer_cards_total < 20:
    dealer_cards_total = sum(dealer_cards)

get_move总是returns'hit',所以break永远不会运行。这是由逻辑错误引起的。

您需要更改以下行:

if move == 'h' or 'Hit':
#and
elif move == 's' or 'Stand':

现在“or”的右边是一个 non-empty 字符串,所以这些 if 将永远是 True

相反,您需要:

if move == 'h' or move == 'Hit':
#and
elif move == 's' or move == 'Stand':

这实际上会按照您的预期分别测试 move 是否等于任一字符串。此外,如果您愿意,也可以使用此约定:

if move in ['h', 'Hit']:
#and
elif move in ['s', 'Stand']: