程序不会重新运行而是执行else语句

问题描述 投票:0回答:1

最近,我在 VS Code 中创建了这个简单的游戏。但是,如果我在游戏要求输入时尝试运行代码,则仅执行未定义的语句(我为输入无效的情况编写的语句,请使用 #UNDEFINED ERROR 检查代码)。程序不会重新运行,而是针对 IDE 中的无效输入执行 else(check code with #UNDEFINED ERROR) 语句。

我的理论是,当我在 VS Code 中按“运行”时,它会输入某些符号来告诉编译器重新运行程序,但是当程序在终端中要求输入时,它会被解释为无效输入,我不确定,因为以前没有发生过。

import random  # Importing the random module to generate random numbers

# Initializing variables
inp = 1
comp_won = user_won = 0

# Printing the welcome message and instructions
print("WELCOME TO GUESS THE NUMBER!\n\nEnter: \n'0' for answer\n'-1' for exit\n\nBEST OF 10:\n")


# Main game loop: continues until the user inputs -1 or either player wins 3 rounds
while int(inp) != -1 and user_won != 3 and comp_won != 3:
    try_remain = 7  # Number of attempts for each round
    num_to_guess = random.randint(1, 100)  # Generating a random number between 1 and 100


    # Loop for each round: continues until attempts run out or the user guesses correctly
    while try_remain > 1:
        inp = input(f"Guess the number ({try_remain-1} attempts left): ")  # Prompting user for input
        
        if inp.isdigit():  # Checking if the input is a digit
            if int(inp) == num_to_guess:  # If the guess is correct
                user_won += 1
                print(f"You won this round!!!\nScore: {user_won}:{comp_won}\n")
                break

            elif num_to_guess < int(inp) <= 100:  # If the guess is too high
                print("Hint: The number is lesser")
                try_remain -= 1

            elif int(inp) == 0:  # Special case for input 0
                try_remain -= 6

            elif int(inp) == -1:  # Special case for input -1
                print(f"\nThe number was {num_to_guess}")
                print("Exiting program...")
                break

            elif 0 < int(inp) < num_to_guess:  # If the guess is too low
                print("Hint: The number is greater")
                try_remain -= 1

            else:  # If the input is out of the valid range
                print("Input should be an integer between 1-100")

        else:  #UNDEFINED ERROR If the input is not a digit
            with open(r'prize.txt', 'a+') as f:  # Opening the prize file
                f.seek(0)
                l = [li.strip() for li in f.readlines()]  # Reading the prize codes


                if inp.upper() in l:  # Checking if the input matches a prize code
                    print(f"\nThe number was {num_to_guess}")
                    user_won += 1
                    print(f"You won this round!!!\nScore: {user_won}:{comp_won}\n")
                    l.remove(inp)  # Removing the used prize code
                    with open(r"prize.txt", 'w') as f:  # Writing the updated prize codes back to the file
                        for it in l:
                            f.write(f"{try_remain}\n")
                    inp = 1
                    break

            print("Input should be an integer between 1-100")


    else:  # If the user fails to guess the number within the allowed attempts
        print(f"The number was {num_to_guess}")
        comp_won += 1
        print(f"You lost this round!!!\nScore: {user_won}:{comp_won}\n")



# End of game: printing the final scores and determining the winner
else:
    print(f"Your score: {user_won}\nComputer score: {comp_won}\n")
    if user_won > comp_won and int(inp) != -1:
        print("You won the game!!!")
        prize = "".join(random.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 4))  # Generating a random prize code
        with open(r"prize.txt", 'a') as f:  # Saving the prize code to the file
            f.write(f"{prize}\n")
            print(f"Use code-{prize} in the next round for an instant victory")
    else:
        print("Computer won!!!")

#ELSE 或未定义语句:

else:  # If the input is not a digit
                with open(r'prize.txt', 'a+') as f:  # Opening the prize file
                f.seek(0)
                l = [li.strip() for li in f.readlines()]  # Reading the prize codes


                if inp.upper() in l:  # Checking if the input matches a prize code
                    print(f"\nThe number was {num_to_guess}")
                    user_won += 1
                    print(f"You won this round!!!\nScore: {user_won}:{comp_won}\n")
                    l.remove(inp)  # Removing the used prize code
                    with open(r"prize.txt", 'w') as f:  # Writing the updated prize codes back to the file
                        for it in l:
                            f.write(f"{try_remain}\n")
                    inp = 1
                    break

            print("Input should be an integer between 1-100")
python visual-studio input compiler-errors ide
1个回答
0
投票

你可能应该做

while int(inp) != -1 and user_won < 3 and comp_won < 3:
while try remaining is > 0:

还有缩进:

        if inp.isdigit():  # Checking if the input is a digit
            ...

        elif inp == '-1':  # Special case for input -1
            print(f"\nThe number was {num_to_guess}")
            print("Exiting program...")
            break

        else:  # If the input is not a digit
            with open('prize.txt', 'a+') as f:  # Opening the prize file
                f.seek(0)
                l = [li.strip() for li in f.readlines()]  # Reading the prize codes
© www.soinside.com 2019 - 2024. All rights reserved.