简体   繁体   English

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

[英]How do I check if the user has entered a number?

I making a quiz program using Python 3. I'm trying to implement checks so that if the user enters a string, the console won't spit out errors.我使用 Python 3 制作了一个测验程序。我正在尝试实施检查,以便在用户输入字符串时,控制台不会吐出错误。 The code I've put in doesn't work, and I'm not sure how to go about fixing it.我输入的代码不起作用,我不知道如何修复它。

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)

You need to catch the exception already in the first if clause.您需要在第一个if子句中捕获异常。 For example:例如:

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

I've also removed the val = int(input()) clause - it seems to serve no purpose.我还删除了val = int(input())子句 - 它似乎没有用。

EDIT编辑

If you want to give the user more than one chance to answer the question, you can embed the entire thing in a while loop:如果您想给用户多次回答问题的机会,您可以将整个内容嵌入一个 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")

This will loop eternally until the right answer is given, but you could easily adapt this to keep a count as well to give the user a fixed number of trials.这将永远循环,直到给出正确的答案,但您可以轻松地调整它以保持计数以及为用户提供固定数量的试验。

Change改变

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

to

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

The .isdigit() method for strings will check if the input is an integer.字符串的.isdigit()方法将检查输入是否为整数。 This, however, will not work if the input is a float.但是,如果输入是浮点数,这将不起作用。 For that the easiest test would be to attempt to convert it in a try/except block, ie.为此,最简单的测试是尝试在 try/except 块中转换它,即。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM