2015-10-20 71 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.") 
相關問題