【问题标题】:How do I check if the user has entered a number?如何检查用户是否输入了数字?
【发布时间】:2015-10-20 09:03:29
【问题描述】:

我使用 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)

【问题讨论】:

  • 有什么不好的?
  • 如果我输入一个字符串,无论如何都会出现错误,如果我输入正确的答案,那么问题就会停止,我必须按 Enter 才能获得下一个问题。如果我答错了,什么也不会发生。
  • 你的 if 语句 if int(input()) == op(num1, num2) 在你的 try 语句之前将 str 转换为 int

标签: python python-3.x


【解决方案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")

这将永远循环,直到给出正确的答案,但您可以轻松调整它以保持计数以及为用户提供固定数量的试验。

【讨论】:

  • 这行得通,谢谢。是否可以循环问题,以便用户有另一个机会回答问题?
  • 您可以为此目的将其嵌入到 while 循环中,是的。我将编辑我的答案。
【解决方案2】:

改变

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

【讨论】:

    猜你喜欢
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-23
    • 2023-03-27
    • 1970-01-01
    • 2012-08-17
    • 2019-03-09
    相关资源
    最近更新 更多