Python3 Try / Except Block

时间:2015-07-24 18:55:19

标签: python python-3.x error-handling try-catch except

有人可以帮我理解以下问题......

我在简单的猜数游戏中执行try / except块时遇到问题。如果我删除初始输入的整数部分,包含我的错误处理的函数工作正常。但是如果我这样做,游戏的其余部分就不起作用,因为根据我的理解,Python3接受输入并将其存储为字符串。那么如何才能执行异常?非常感谢任何帮助。

谢谢,

# number game
import random




print ("Welcome to the guessing number game!\n\n")

winning_number= random.randrange(1, 11)
guess = int(input("Can you guess the lucky number.\nHint it's between 1 and 10!\n"))


def is_number(guess):
    try:
        int(guess)
    except ValueError:
        print ('You need to type a number\n')
        guess = int((input("Please input a number\n")))
        game(guess)



def compare(guess):
    if guess > winning_number:
        print ("Wrong, you're guess is too high.\n")
        guess = int(input("Guess againn\n"))
        game(guess)
    else:
        print ("Wrong, you're guess is too low.\n")
        guess = int(input("Guess again\n"))
        game(guess)



def game(guess):
    is_number(guess)
    if guess == winning_number:
        print ("You win!, You guessed the number!")
    else:
        compare(guess)

game(guess)

这是我输入除整数以外的任何内容时得到的结果......

欢迎来到猜数游戏!

你能猜出幸运数字。 提示它在1到10之间! F Traceback(最近一次调用最后一次):   文件“C:/Users/mickyj209/PycharmProjects/Practice/NumberGuess.py”,第10行,in     guess = int(输入(“你能猜出幸运数字。\ n提示它在1到10之间!\ n”)) ValueError:int()的基数为10的无效文字:'f'

使用退出代码1完成处理

1 个答案:

答案 0 :(得分:0)

您忘记保存时间值(guess = int(guess)),而不是return那里的任何内容,并且您只是让程序运行该功能而不是制作基于结果的决定。您在异常处理中也有一个int(input(...,它本身可以生成一个不会被捕获的异常。最初的猜测也不在try块中。

你可以重构这个程序:

def game():

    print ("Welcome to the guessing number game!\n\n")

    winning_number = random.randrange(1, 11)
    print("Can you guess the lucky number?\nHint: it's between 1 and 10!\n")
    while 1:
        try:
            guess = int(input("Please input a number\n"))
        except ValueError:
            continue
        if guess > winning_number:
            print('Wrong - your guess is too high.')
        elif guess < winning_number:
            print('Wrong - your guess is too low.')
        else:
            print('You win! You guessed the number!')
            break