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

时间:2017-10-08 15:40:15

标签: python validation loops feedback

我是学习Python的新手,只有6章进入 Starting Out with 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()

2 个答案:

答案 0 :(得分:0)

问题在于此部分代码的其他条件。

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. "))

更新重复变量后你没有做任何事情,这就是程序刚刚终止的原因。您可能希望从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.")

并相应地修改您的程序。

答案 1 :(得分:0)

如果你想重复一些事情,请使用循环。另外,要重复整个程序,请不要再次调用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