如何检查用户是否输入了号码?

时间:2015-10-20 09:03:29

标签: python python-3.x

我使用Python 3制作测验程序。我正在尝试实施检查,以便在用户输入字符串时,控制台不会吐出错误。我输入的代码不起作用,我不知道如何修复它。

import random
import operator
operation=[
    (operator.add, "+"),
    (operator.mul, "*"),
    (operator.sub, "-")
    ]
num_of_q=10
score=0
name=input("What is your name? ")
class_num =input("Which class are you in? ")
print(name,", welcome to this maths test!")

for _ in range(num_of_q):
    num1=random.randint(0,10)
    num2=random.randint(1,10)
    op,symbol=random.choice(operation)
    print("What is",num1,symbol,num2,"?")
    if int(input()) == op(num1, num2):
        print("Correct")
        score += 1
        try:
            val = int(input())
        except ValueError:
            print("That's not a number!")
    else:
     print("Incorrect")

if num_of_q==10:
    print(name,"you got",score,"/",num_of_q)

2 个答案:

答案 0 :(得分:1)

您需要在第一个if子句中捕获异常。例如:

for _ in range(num_of_q):
    num1=random.randint(0,10)
    num2=random.randint(1,10)
    op,symbol=random.choice(operation)
    print("What is",num1,symbol,num2,"?")
    try:
        outcome = int(input())
    except ValueError:
        print("That's not a number!")
    else:
        if outcome == op(num1, num2):
            print("Correct")
            score += 1
        else:
            print("Incorrect")

我还删除了val = int(input())条款 - 似乎没有用处。

修改

如果您想让用户有多个机会回答这个问题,您可以将整个内容嵌入到while循环中:

for _ in range(num_of_q):
    num1=random.randint(0,10)
    num2=random.randint(1,10)
    op,symbol=random.choice(operation)
    while True:
        print("What is",num1,symbol,num2,"?")
        try:
            outcome = int(input())
        except ValueError:
            print("That's not a number!")
        else:
            if outcome == op(num1, num2):
                print("Correct")
                score += 1
                break
            else:
                print("Incorrect, please try again")

这将永远循环,直到给出正确的答案,但您可以轻松地对此进行调整,以便为用户提供固定数量的试验。

答案 1 :(得分:0)

更改

print("What is",num1,symbol,num2,"?")
if int(input()) == op(num1, num2):

print("What is",num1,symbol,num2,"?")
user_input = input()
if not user_input.isdigit():
    print("Please input a number")
    # Loop till you have correct input type
else:
    # Carry on

字符串的.isdigit()方法将检查输入是否为整数。 但是,如果输入是浮点数,则这将不起作用。为此,最简单的测试是尝试在try / except块中转换它,即

user_input = input()
try:
    user_input = float(user_input)
except ValueError:
    print("Please input a number.")