gpt4 book ai didi

使用 def 函数重新运行 Python 程序

转载 作者:行者123 更新时间:2023-11-30 21:57:17 25 4
gpt4 key购买 nike

这个想法是该程序将用于具有许多功能。根据用户输入,它们将被发送到程序中的某个 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

最后,QuizAnswer 都不应该以大写字母开头。根据 PEP8 标准 https://realpython.com/python-pep8/#naming-styles函数和变量名称应以小写字母开头。这可能看起来微不足道,但即使在 Stack Overflow 问题中,您也可以看到 Answer 与函数名称具有相同的颜色,并且与其他变量不同,因此稍后可能会引起困惑。

关于使用 def 函数重新运行 Python 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55318841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com