想法是该程序将用于具有许多功能。根据用户输入的内容,它们将被发送到程序中的某个def
,并带有最后保存数据的选项。
score = 0
def Quiz():
print ("Welcome to the quiz.")
name = input("Please type your name:")
print ("Answer the question.")
Answer == input ("Please enter the answer to 5+6.")
Quiz()
if Answer == "11":
score = score + 1
print("Your answer is correct and your score is", score)
else:
print ("Your answer is wrong. Your score is", score)
again = str(input("Do you want to play again (type yes or no): "))
if again == "yes":
Quiz()
else:
sys.exit(0)
我只是不确定为什么它不会运行该程序,然后在用户输入yes时循环返回。
任何帮助将不胜感激,我想我已经接近了。
最佳答案
该代码有一些错误。 6502在另一个答案中提到了其中一个:通过具有第二个Quiz(),程序将在运行Quiz函数后返回到该点,因此第二遍执行后它将自动退出。
其他一些事情:Answer == input (' ')
失败,因为==
使Python认为它正在评估等效性,而不是将输入分配给Answer
Answer不是全局变量,也不是传递回主程序,因此当您尝试检查其值时它将失败
从第一句话开始,我不确定您要对过程做些什么,因此需要将Answer定义为全局,或者需要将其从函数中传回,如下所示:
score = 0
def Quiz():
print ("Welcome to the quiz.")
name = input("Please type your name:")
print ("Answer the question.")
Answer = input ("Please enter the answer to 5+6.")
return Answer
while True:
Answer = Quiz()
if Answer == "11":
score = score + 1
print("Your answer is correct and your score is", score)
else:
print ("Your answer is wrong. Your score is", score)
again = str(input("Do you want to play again (type yes or no): "))
if again == "no":
break
但是整个过程可以更简单地完成,而无需执行以下步骤:
score = 0
while True:
print ("Welcome to the quiz.")
name = input("Please type your name:")
print ("Answer the question.")
Answer = input ("Please enter the answer to 5+6.")
if Answer == "11":
score = score + 1
print("Your answer is correct and your score is", score)
else:
print ("Your answer is wrong. Your score is", score)
again = str(input("Do you want to play again (type yes or no): "))
if again == "no":
break
最后,
Quiz
和Answer
都不应真正以大写字母开头。根据PEP8标准,https://realpython.com/python-pep8/#naming-styles函数和变量名称应以小写字母开头。看起来似乎很琐碎,但即使在“堆栈溢出”问题中,您也可以看到Answer具有与函数名称相同的颜色,并且与其他变量不同,因此稍后可能会引起混淆。关于python - 使用def函数重新运行Python程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55318841/