Python 如何检查用户是否输入了数字?
我正在使用Python 3制作一个测验程序。我试图实现检查,这样如果用户输入字符串,控制台就不会抛出错误。我输入的代码不起作用,我不知道如何着手修复它Python 如何检查用户是否输入了数字?,python,python-3.x,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? "
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)
改变
到
字符串的.isdigit()
方法将检查输入是否为整数。
但是,如果输入为浮点,则此操作将不起作用。为此,最简单的测试是尝试在try/except块中转换它,即
user_input = input()
try:
user_input = float(user_input)
except ValueError:
print("Please input a number.")
您需要捕获第一个
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")
这将一直循环,直到给出正确答案,但您可以轻松地调整它,以保持计数,并为用户提供固定的尝试次数。这有什么不起作用?如果我键入字符串,错误仍然会出现,如果我键入正确答案,则问题停止,我必须按enter键才能获得下一个问题。如果我得到了错误的答案,什么都不会发生。你有你的If语句
If int(input())==op(num1,num2)
在你的try语句之前将str转换为int这很有效,谢谢。是否可以循环该问题,以便用户有另一次机会回答该问题?您可以为此目的将其嵌入while循环中,是的。我将编辑我的答案。
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")
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")