清理程序

时间:2018-10-01 11:34:37

标签: python try-catch

我终于开始工作了!但是由于某种原因,程序会打印出先前的错误语句(太高或太低,或者请在之间输入值...),如果用户输入了尝试捕获的内容,则还会显示值错误消息。谁能解释为什么?也欢迎任何缩短/清除操作。对不起,任何错误。谢谢!

'''
This is a guessing game that finds a random number, and then
Tells the user if their guess is too low or too high.  It will also give
Error messages for any numbers outside of the accepted range, and will also
Give errors for anything not an integer.
At the end (if the user guesses correctly) it will ask if the
User would like to play again or quit.
'''

import random


def start_here():
    print("Welcome to the guessing game!")
    play_game()


def play_game():

    random_number = random.randrange(1, 100)
    correct = False
    user_guess = True

    while not correct:

        try:
            user_guess = int(input("Enter your guess: "))
        except ValueError:
            print("Please only use integers")

        if user_guess > 100 or user_guess < 1:
            print("Please only enter numbers between 1 and 100!")

        elif user_guess > random_number:
            print("Too high, try again. ")

        elif user_guess < random_number:
            print("Too low, try again! ")

        elif user_guess == random_number:
            break

    if user_guess == random_number:
        replay = (input("Great!  You guessed it! would you like to play again? y or n"))
        if replay == "y":
            start_here()
        else:
            print("See ya later!")


start_here()

2 个答案:

答案 0 :(得分:1)

请记住,无论是否抛出异常,都会执行try-except块之后的代码。如果调用了except块,则您希望您的代码跳过while循环中的其余语句,并在循环的下一次迭代时跳过continue,在此提示用户再次输入。可以通过在continue块中使用except关键字来实现,如下所示:

try:
     user_guess = int(input("Enter your guess: "))
except ValueError:
     print("Please only use integers")
     continue

continue语句指示解释器跳过循环当前迭代中的其余语句。然后,控制流可以根据循环条件重新进入循环或退出。

现在您的代码按照预期的方式运行,这是使代码更简洁的方法:

首先,Python中有一个简洁的功能,可让您编写诸如not 1 <= user_guess <= 100之类的条件。这些条件的读取要快得多,您可以在代码中将其替换。

第二,start_here()函数是多余的。您可以通过以下类似的修改轻松地替换play_game()

import random

def play_game():
    print("Welcome to the guessing game!")  #Modification here
    random_number = random.randrange(1, 100)
    correct = False
    user_guess = True

    while not correct:

        try:
            user_guess = int(input("Enter your guess: "))
        except ValueError:
            print("Please only use integers")
            continue #Modification here

        if not 1<=user_guess<=100: #Modification here
            print("Please only enter numbers between 1 and 100!")

        elif user_guess > random_number:
            print("Too high, try again. ")

        elif user_guess < random_number:
            print("Too low, try again! ")

        elif user_guess == random_number:
            break

    if user_guess == random_number:
        replay = (input("Great!  You guessed it! would you like to play again? y or n"))
        if replay == "y":
            play_game()  #Modification here
        else:
            print("See ya later!")


play_game()  #Modification here

或者您可以像这样用while循环完全替换play_game()函数:

import random

replay = 'y'  #Modification here

while replay == 'y': #Modification here
    print("Welcome to the guessing game!")
    random_number = random.randrange(1, 100)
    correct = False
    user_guess = True

    while not correct:

        try:
            user_guess = int(input("Enter your guess: "))
        except ValueError:
            print("Please only use integers")
            continue

        if not 1<=user_guess<=100 :
            print("Please only enter numbers between 1 and 100!")

        elif user_guess > random_number:
            print("Too high, try again. ")

        elif user_guess < random_number:
            print("Too low, try again! ")

        elif user_guess == random_number:
            break

    if user_guess == random_number: #Modification here
        replay = input("Great!  You guessed it! would you like to play again? y or n")


print("See ya later!") #Modification here

答案 1 :(得分:0)

这里:

while not correct:

    try:
        user_guess = int(input("Enter your guess: "))
    except ValueError:
        print("Please only use integers")

    if user_guess > 100 or user_guess < 1:
       # etc

如果用户输入的值不是有效的int,则显示错误消息,但仍要根据随机数测试该值。相反,您应该跳过循环的其余部分,或者提取将用户输入输入到自己的循环中的部分。通常,一个函数只能做一件事,然后使用另一个函数来控制整个程序的流程:

def get_num():
    while True:
        try:
            user_guess = int(input("Enter your guess: ").strip())
        except ValueError:
            print("Please only use integers")
            continue

        if user_guess > 100 or user_guess < 1:
            print("Please only enter numbers between 1 and 100!")
            continue

        return user_guess

def again():
    replay = input("would you like to play again? y or n"))
    return replay.strip().lower() == "y"

def play_game():
    random_number = random.randrange(1, 100)
    while True:
        user_guess = get_num()
        if user_guess > random_number:
            print("Too high, try again. ")
        elif user_guess < random_number:
            print("Too low, try again! ")
        else:
            # if it's neither too high nor too low then it's equal...
            break

    # no need to test again, we can only get here when the user
    # found the number
    print("Great!  You guessed it!")

def main():
    print("Welcome to the guessing game!")
    while True:
        play_game()
        if not again():
            break


if __name__ == "__main__":
    main()