【发布时间】:2017-04-12 04:46:21
【问题描述】:
from random import randint
user_name = input("\nHello, please enter your name: ").title().strip()
print ("Alright",user_name,"Welcome to your maths quiz")
score=0
incorrect = 0
for question_num in range(1, 11):
while True:
try:
size = ["bigger", "smaller"]
rand = randint(0,100)
rand2 = randint(0,100)
size_question = randint(0, len(size) - 1)
print('\nQuestion number: {}'.format(question_num))
question_num += 1
print ("Which number is", size[size_question], rand, "or", rand2)
answer = int(input ("What is your answer: "))
if size[size_question] == "bigger":
if rand > rand2 and rand == answer:
print("correct", rand, "is", size[size_question])
score += 1
elif rand2 > rand and rand2 == answer:
print("correct", rand2, "is", size[size_question])
score += 1
elif size[size_question] == "smaller":
if rand < rand2 and rand == answer:
print("correct", rand, "is", size[size_question])
score += 1
elif rand2 < rand and rand2 == answer:
print("correct", rand2, "is", size[size_question])
score += 1
except ValueError:
print ("Incorrect")
if score > 0:
score -= 1
【问题讨论】:
-
为什么值错误不起作用?
-
“不工作”是什么意思?你的预期输出是什么,你得到了什么?您认为在哪里引发了
ValueError异常? -
当答案不正确时,不正确不打印!
-
程序如何知道它是不正确的,在任何时候都不会引发
ValueError。异常块仅在引发该异常时才执行。看起来你只需要条件逻辑,而不是异常逻辑。 -
ValueError仅在用户未输入整数时才会在您的代码中引发,如果答案错误则不会引发。如果答案是错误的,什么都不会发生。while True循环也没有什么可以破坏它的,这意味着这段代码将永远运行。正如@AChampion 所说,您需要使用条件逻辑,这里甚至不需要except子句,您可以使用isdigit()测试整数
标签: python python-3.6