2015-10-20 67 views
-1

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

“不行”如何? – TigerhawkT3

+0

什么不适用于它? – Academiphile

+0

如果我输入一个字符串,无论如何都会出现错误,如果我输入正确的答案,那么问题就会停止,我必须按Enter才能获得下一个问题。如果我得到答案错误没有任何反应。 – CyberSkull311

回答

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

这将循环永远,直到给出了正确的答案,但你可以很容易地适应这一点,以保持计数,并给用户一个固定数量的试验。

+0

这工作,谢谢。是否有可能循环问题,以便用户有另一个机会来回答问题? – CyberSkull311

+0

为了这个目的,你可以在while循环中嵌入它,是的。我会编辑我的答案。 –

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.") 
相关问题