Python-使用try / except猜测数字

时间:2018-12-05 20:59:21

标签: python try-except

嗨,我是python的新手,我搜索了一些练习和学习更多的迷你挑战,现在我正在做一个“猜数字”脚本,它起作用了,但是现在我想在其中添加一个try / except当用户输入非整数时阻止,这是我现在拥有的代码:

from random import *
print('Guess the number')

def check_correct(u_guess, num):
    while True:
        if u_guess < num:
            print('Guess is high!')
            while True:
                try:
                    u_guess = int(input('What number do you think is? (Between 1 and 5): '))
                except ValueError:
                    print('Invalid number try again!')
        elif u_guess > num:
            print('Guess is low!')
            while True:
                try:
                    u_guess = int(input('What number do you think is? (Between 1 and 5): '))
                except ValueError:
                    print('Invalid number try again!')
        elif u_guess == num:
            print('You got it!')
            break

def guess():
    num = randint(1, 5)
    u_guess = None
    while u_guess == None:
        try:
            u_guess = int(input('What number do you think is? (Between 1 and 5): '))
            check_correct(u_guess, num)
        except ValueError:
            print('Invalid number try again!')
guess()

这是我的输出:

$ python Project2.py

    Guess the number
    What number do you think is? (Between 1 and 5): 1
    Guess is high!
    What number do you think is? (Between 1 and 5): 2
    What number do you think is? (Between 1 and 5): 2
    What number do you think is? (Between 1 and 5):
    Invalid number try again!
    What number do you think is? (Between 1 and 5): Traceback (most recent call last):
      File "Project2.py", line 35, in <module>
        guess()
      File "Project2.py", line 31, in guess
        check_correct(u_guess, num)
      File "Project2.py", line 11, in check_correct
        u_guess = int(input('What number do you think is? (Between 1 and 5): '))
    EOFError

1 个答案:

答案 0 :(得分:0)

check_correct唯一要做的是,如果猜测正确,则返回True,否则返回False。它还可以输出描述比较结果的消息。

import random  # Never use from <whatever import *
print('Guess the number')

def check_correct(u_guess, num):
    if u_guess < num:           # You had the roles of u_guess and num reversed
        print('Guess is low!')
        return False
    elif u_guess > num:
        print('Guess is high')
        return False
    else:  # u_guess == num
        print('You got it!')
        return True

guess处理所有用户输入,调用check_correct确定是否 外循环应终止。内部循环一直持续到int(uguess)不会引发异常。

def guess():
    num = random.randint(1, 5)
    while True:
        while True:
            u_guess = input('What number do you think it is? (Between 1 and 5)')
            try:
                u_guess = int(u_guess)
                break
            except ValueError:
                print('Invalid number, try again!')
        if check_correct(u_guess, num):
            break

guess()