【问题标题】:Python - Guess the number with try/exceptPython - 用 try/except 猜数字
【发布时间】:2018-12-06 05:19:45
【问题描述】:

嗨,我是 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

【问题讨论】:

  • 您没有使用您的输入,而是再次请求输入。这是一个错误。退出你的函数,让外部 while 循环完成工作。
  • 如前所述,您永远不会使用break 来退出无限重试循环。无论是否引发异常,您都会回到该循环的顶部。
  • 但正如 deets 指出的那样,check_correct 做得太多了。它应该检查该值,输出猜测值是过高还是过低的描述,然后返回 True 或 False。 guess 是唯一真正应该接受用户输入的函数。

标签: python try-except


【解决方案1】:

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) not 引发异常。

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()

【讨论】:

    猜你喜欢
    • 2019-06-26
    • 2011-05-08
    • 1970-01-01
    • 2011-04-25
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    相关资源
    最近更新 更多