我需要在while循环中添加验证。
然而,当我使用此验证时,它不起作用,而只是提出错误消息,说我没有使用基数10 /整数,当我希望它提出验证错误消息并让用户再试一次。
我不知道是否在while循环中使用它会使我使用的验证有所不同,是吗?
我还需要将此“def inputNumber(message):”更改为我的输入存储的内容吗?
这个“userInput = int(输入(消息))”到我输入的内容是什么?
import time
import random
question = 0
score = 0
name = input("What is your full name?")
print ("Hello " + name, "welcome to The Arithmetic Quiz. Use integers to enter the answer!")
time.sleep(2)
operands1 = list(range(2, 12))
operators = ["+","-","x"]
operands2 = list(range(2, 12))
while question < 10:
operand1 = random.choice(operands1)
operand2 = random.choice(operands2)
operator = random.choice(operators)
def inputNumber(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return userInput
break
user_answer =int(input('{} {} {} = '.format(operand1, operator, operand2)))
答案 0 :(得分:0)
我怀疑你是否希望在while循环中拥有你的函数定义,就像你在这里做的那样:
while question < 10:
...
def inputNumber(message):
...
相反,您可以在循环外部定义 函数,并在其他地方循环调用x次。 E.g。
def inputNumber(message):
...
return userInput
while question < 10:
# pick random numbers/operators
...
# call inputNumber() with numbers/operators as message. Return user_answer
user_answer = int(inputNumber('{} {} {} = '.format(operand1, operator, operand2)))
# check if the answer is correct
...
# increment question so it doesn't run infinitely
question += 1
答案 1 :(得分:0)
@ user6104134已经解决了这个问题;但是,我想为其他有类似问题的人提供答案。
import random
import time
question = 0
score = 0
def inputnumber(prompt):
while True:
response = raw_input(prompt)
try:
if isinstance(response, int):
return int(response)
else:
print "Not an integer! Try again."
except ValueError:
print "Not an integer! Try again."
name = raw_input("What is your full name? ")
print ("Hello " + name, "welcome to The Arithmetic Quiz. Use integers to enter the answer!")
time.sleep(2)
operands1 = list(range(2, 12))
operators = ["+", "-", "x"]
operands2 = list(range(2, 12))
while question < 10:
operand1 = random.choice(operands1)
operand2 = random.choice(operands2)
operator = random.choice(operators)
user_answer = int(inputnumber('{} {} {} = '.format(operand1, operator, operand2)))
question += 1
首先,您应该在脚本之外声明函数定义,并通过标识符&#39; inputNumber()&#39;
调用函数另请注意Try / Except和PEP 8 Style Guide兼容格式的细微变化。