(Python) 验证循环未按预期更新变量

(Python) Validation loop not updating variable as expected

我刚开始学习 Python,只读了 6 章 从 Python 开始,第 4 版。我正在尝试编写一个非常简化的二十一点游戏,但我目前的问题在于如果用户想要尝试重复游戏(即“你想再玩一次吗?”)。当我输入无效的选择时,正确的验证消息出现。但是当再次提示问题时,repeat 变量没有用新输入更新,程序只是终止,即使用户选择再次播放。我做错了什么?我正在附加整个程序如下:

# Import the random functionality
import random

# A nifty welcome message
print("Welcome to my Black Jack program! Let's play!\n")

# Define the function for dealing individual cards
def deal_card():
    # Because a deck of cards has face cards and aces, we must assign numerical values to these cards.
    Jack = 10
    Queen = 10
    King = 10
    Ace = 1
    # We make a range from which the random.randrange can choose cards.
    cards = [Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King]
    # Another variable to define what is being selected.
    drawn_card = cards[random.randrange(1, 13)]
    # The return function stores this data until it is recalled later.
    return drawn_card

# This function gives us the user's card value.
def get_player_score():
    # The player is dealt two cards, so the deal_card function is called twice.
    first_player_card = deal_card()
    second_player_card = deal_card()
    # The value is calculated by adding the two cards.
    sum_player_cards = first_player_card + second_player_card
    print ("Your card total is: ", sum_player_cards, ".", sep="")
    # This primes the feedback loop of "hitting" and "staying"
    choice = int(input("\nWould you like to hit or stay?\nEnter 1 for 'hit' or 2 for 'stay'. "))
    # The player should only have this choice when their card value is not over 21.
    while sum_player_cards < 21:
        if choice == 1:
            new_card = deal_card()
            sum_player_cards = sum_player_cards + new_card
            print ("\nYour new total is: ", sum_player_cards, ".", sep="")
            # Again, if the card value is over 21, their turn is over.
            if sum_player_cards < 21:
                choice = int(input("\nWould you like to to hit or stay? Enter 1 for 'hit' or 2 for 'stay'. "))
        # If the card value is over 21, then the function ends.
        elif choice == 2:
            return sum_player_cards
        # Validation check.
        else:
            print("\nPlease choose 'hit' or 'stay'.")
            choice = int(input("\nAgain, would you like to hit or stay? Enter 1 for 'hit' or 2 for 'stay'. "))
    # If somehow the card value is over 21 at this point, the function ends.
    if sum_player_cards >= 21:
        return sum_player_cards

# Now we determine the dealer's score in much the same way.
def get_dealer_score():
    # Two cards are drawn for the dealer.
    first_dealer_card = deal_card()
    second_dealer_card = deal_card()
    sum_dealer_cards = int(first_dealer_card + second_dealer_card)
    # Here, we must automatically decide for the dealer that if their card value is below 17, they must draw another card.
    while sum_dealer_cards <= 16:
        another_dealer_card = deal_card()
        sum_dealer_cards = sum_dealer_cards + another_dealer_card
    # The previous loop stops when their card value is above 16.
    if sum_dealer_cards > 16:
        print("\nThe dealer's card total is: ", sum_dealer_cards, ".", sep="")
    # The value for the dealer cards is now stored.
    return sum_dealer_cards

# The main function controls the other major functions and determines if the program is repeated.
def main():
    # These new variables allow for the player and dealer card values to be compared.
    player_score = get_player_score()
    dealer_score = get_dealer_score()
    # Now we must define the various end game conditions.
    if player_score > dealer_score and player_score <= 21:
        print("\nYou win!")
    elif dealer_score > player_score and dealer_score <= 21:
        print("\nThe dealer wins!")
    elif dealer_score <= 21 and player_score > 21:
        print("\nYou've gone bust! Dealer wins!")
    elif dealer_score > 21 and player_score <= 21:
        print("\nThe dealer busts! You win!")
    elif dealer_score > 21 and player_score > 21:
        print("\nYou've both gone bust! Nobody wins!")
    elif player_score == dealer_score:
        print("\nPush! Nobody wins!")
    # Prime the variable in order to replay the game.
    repeat = int(input("\nDo you want to play again?\nIf 'Yes', enter 1. If 'No', enter 2. "))
    if repeat == 1:
        # This repeats the entire main function, which controls the rest of the program.
        main()
    elif repeat == 2:
        # Here we end the program.
        return repeat
    else:
        # Validation check
        print("Please enter a valid choice.")
        repeat = int(input("Again, do you want to play again?\nIf 'Yes', enter 1. If 'No', enter 2. "))


# And this short line activates the rest of the program.
main()

问题出在这部分代码的 else 条件下。

repeat = int(input("\nDo you want to play again?\nIf 'Yes', enter 1. If 'No', enter 2. "))
if repeat == 1:
    # This repeats the entire main function, which controls the rest of the program.
    main()
elif repeat == 2:
    # Here we end the program.
    return repeat
else:
    # Validation check
    print("Please enter a valid choice.")
    repeat = int(input("Again, do you want to play again?\nIf 'Yes', enter 1. If 'No', enter 2. "))

您在更新 repeat 变量后没有做任何事情,这就是程序刚刚终止的原因。您可能希望从 main 函数中删除该代码,并在调用 main() 之后添加它,如下所示。

main()
while True:
    repeat = int(input("\nDo you want to play again?\nIf 'Yes', enter 1. If 'No', enter 2. "))
    if repeat == 1:
        main()
    elif repeat == 2:
        break
    else:
        print("Please enter a valid choice.")

并相应地修改您的程序。

如果您想重复某些内容,请使用循环。另外,要重复整个程序,不要递归调用 main,而是将其主体包裹在一个循环中。例如,您可以这样编写代码:

def main():
    while True:  # infinite loop, programm will repeat until return (or break) is called

        # stuff

        while True:  # another infinite loop
            repeat = int(input("Again, do you want to play again?\nIf 'Yes', enter 1. If 'No', enter 2. "))
            if repeat == 1:
                break  # exit input loop, but not main loop, programm starts over
            elif repeat == 2:
                return # exit main
            else:
               print("Please enter a valid choice.") # invalid input, input loop keeps going