python 不从 def 段落返回变量

python not returning variables from a def paragraph

我的 python 代码有问题我一直在尝试为我的 GCSE 做一个数学测验,但我 运行 遇到了一个问题。

return 函数没有 return 任何变量,如下所示我已经说明了需要 'returned' 的变量,除非我使用了错误的函数。

我的目标是让 numgen 生成数字,然后在 def question 中使用这些数字来询问用户答案,然后 def correct 告诉用户用户如果问题是正确的。

import random
import time
Decision = 'neither'
print("\n\n\n\n\n\n")

Name = input("Hello what is your name?")

print("...")

time.sleep(1)

print("Hello",Name,"are you ready for the maths quiz?")

while Decision.lower() != "yes" or "no":
    Decision = input("Type either\n'yes'\nor\n'no'")

    if Decision.lower() == "yes":
        print("Ok, we will proceed")
        break

    elif Decision == "no":
        print("Please come back when you are ready")
        exit(0)

    else:
        print("please type again either 'yes' or 'no'")

marks = 0

def numgen():
    num1 = random.randint(1,40)
    numlist = random.choice(['*','/','+','-'])
    num2 = random.randrange(2,20,2)
    answer = eval(str(num1) + numlist + str(num2))
    return(num1, numlist, num2, answer)

score = 0

def question (num1, numlist,num2, answer):
    print("This question is worth 10 marks.")
    print ("The question is:",num1, numlist, num2)
    Q1 = input('What is your answer?')
    Q1 = float(Q1)
    return(Q1)

def correct(Q1):
    if Q1 == answer:
        print("Well done you got it right.")
        score = score + 10
    else:
        print("you were incorrect the asnwer was:",answer)
        return (score)

questions = 0
while questions < 10:
    numgen()
    question(num1,num2,answer,numlist)
    correct(Q1)


print(marks)

编辑: 好的,我感谢大家的帮助,但我仍然有问题,因为在这一行 print ("The question is:",num1, numlist, num2) 中,num2 是出于某种原因出现答案的地方,我不知道是什么原因造成的,但任何人都非常烦人帮助。这是在我编辑代码以包含

之后
num1,num2,numlist,answer=numgen()
Q1=question(num1,num2,answer,numlist)
score = int(score)
score = correct(score, Q1)

例如,如果我有:

the question is: 24 + 46

答案是 46。我应该放弃使用 def命令?预先感谢您的帮助。

num1, num2, answer, numlist = numgen()

这会起作用,因为你 return 一些东西,但你没有将 returned 值分配给任何东西,以便以后可以使用它们。

这叫做拆包。

完全一样

a, b = 1, 3

您还可以使用元组来切换变量值:

a, b = b, a

好吧,您没有使用从 numgen 函数返回的值。尝试将程序的最后一部分更改为:

while questions < 10:
    num1,num2,answer,numlist = numgen() # here you save the output of numgen
    question(num1,num2,answer,numlist) # and then use it
    correct(Q1)

编辑:

深入了解您的代码后,您似乎不了解作用域。 看看这个 Short Description of the Scoping Rules?

这个想法是一个变量有一个 "place" 定义并且可以访问的地方。当您在函数中定义变量时(在 def 内部),它不会自动从不同的方法访问。所以在你的例子中,函数 correct(Q1) 看不到 answer 中定义的变量 numgen 并且它没有作为参数传递给它并且它不是 "global"变量

编辑:

你现在的问题是参数的顺序,

你这样称呼它:

question(num1,num2,answer,numlist)

但它被定义为:

def question (num1, numlist,num2, answer):

看到顺序的不同了吗?它们的顺序应该相同

好吧,您需要将返回值存储在某处:

while questions < 10:
   num1, numlist, num2, answer = numgen()
   Q1 = question(num1,num2,answer,numlist)
   correct(Q1)