如何阻止我的代码在第一个错误时进入无限循环

问题描述 投票:0回答:1
def stick_game():
    num_sticks = 11
    player = 1
    playing = True

    print("***** WELCOME TO NIM! *****")
    print("Each player will take turns removing")
    print("1, 2, or 3 sticks from the initial 11.")
    print("The player who removes the last stick wins!")
    while playing:
        print(f"\nPlayer {player}, it's your turn!")
        print(f"Here are the sticks remaining: {'|' * num_sticks}")

        move = int(input("How many would you like to remove?"))

        while move < 1 or move > 3 or move > num_sticks:
            if move > num_sticks:
                print("Can not take more sticks than remain. Try again:")
            else:
                print(" Invalid move. Try again:")



        num_sticks -= move

        if num_sticks == 0:
            print(f"Invalid move. Try again: Congratulations Player {player}, you win!")
            playing = False

        player = 2 if player == 1 else 1


stick_game()

 your text
我必须输入 4,0,3,3,3,3,2 但输入 4 会将其发送到无限循环(无效循环重试)我无法使用中断。这个磨砂膏有什么想法吗?

python infinite-loop nim-game
1个回答
0
投票

这个循环就是问题所在:

while move < 1 or move > 3 or move > num_sticks:
    if move > num_sticks:
        print("Can not take more sticks than remain. Try again:")
    else:
        print(" Invalid move. Try again:")

您没有在循环中为

move
分配新值,因此它永远保持其错误值。

您需要在循环内放置另一个

input
语句。

© www.soinside.com 2019 - 2024. All rights reserved.