虽然循环在它应该的时候没有中断

While Loop not breaking when it is supposed to

def NewCard():
  draw_card = input("Would you like to draw a new card? 'hit' or 'pass': ").lower()
  if draw_card == "hit":
    new_card =  cards[random.randint(0, cards_length)]
    player_cards.append(new_card)
    print(f"Your new hand is {player_cards}")
  elif draw_card == "pass":
     playerturn = False
     return playerturn 

while playerturn == True:
  Check_Scores()
  NewCard()
ComputerPlays()

应该发生的是,当用户键入“pass”时,while 循环将中断并继续执行下一个代码。但是发生的是循环永远重复。整个块在另一个更大的函数中,所以这就是缩进的原因

NewCard函数中的playerturn变量是局部的,不是全局的。试试这个:

while playerturn == True:
  Check_Scores()
  playerturn = NewCard()
playerturn = True

def NewCard():
  global playerturn
  draw_card = input("Would you like to draw a new card? 'hit' or 'pass': ").lower()
  if draw_card == "hit":
    new_card =  cards[random.randint(0, cards_length)]
    player_cards.append(new_card)
    print(f"Your new hand is {player_cards}")
  elif draw_card == "pass":
     playerturn = False
     return playerturn 

while playerturn == True:
  Check_Scores()
  NewCard()
ComputerPlays()

您需要在 NewCard() 函数中添加一个 global playerturn 才能让您的代码正常工作。这是因为你的 NewCard() 函数中的 playerturn = False 行实际上创建了一个局部变量 playerturn 并将其设置为函数范围内的 False ,它不会影响playerturnNewCard() 函数之外的值。有关 python 范围的更多信息,请阅读此 article

def NewCard():
  draw_card = input("Would you like to draw a new card? 'hit' or 'pass': ").lower()
  if draw_card == "hit":
    new_card =  cards[random.randint(0, cards_length)]
    player_cards.append(new_card)
    print(f"Your new hand is {player_cards}")
  elif draw_card == "pass":
     global playerturn
     playerturn = False
 

while playerturn == True:
  Check_Scores()
  NewCard()
ComputerPlays()

将 playerturn 设置为全局解决了我的问题

这里函数 NewCard() 中的变量 playerturn 是函数本身的局部变量。使用全局变量 playerturn 或如下修改循环:

while playerturn==True:
    Check_Scores()
    playerturn=NewCard()