我试图让我的程序在有人答错问题时运行(即,用户输入的数字太大或太小,它将要求用户再次输入答案)。我尝试使用While True:loops,但这使我的程序有一个无限循环,永远不会结束。任何帮助都将不胜感激
import random
def main() :
# Generate two random numbers between 1 and 100
n1 = random.randint(1,100)
n2 = random.randint(1,100)
# Ask the answer
print("What is the sum:",n1,"+",n2)
attempt = 1
answer = int(input("Answer: "))
if answer != n1 + n2 and answer < n1 + n2:
print("Wrong! The correct answer is greater than " + str(answer) + ".")
else:
if answer != n1 + n2 and answer > n1 + n2:
print("Wrong! The correct answer is less than " + str(answer) + ".")
else:
if answer == n1 + n2:
print("Yes! The correct answer is " + str(answer) + "." + "\n You got it in " + str(attempt) + " attempts.")
exit()
main()
我们可以把代码缩短很多。。。我还添加了注释作为解释
没有我的评论:
此解决方案将适用于多个错误答案,而不会陷入无休止的循环。无论如何,给你:
干杯
相关问题 更多 >
编程相关推荐