2015-09-22 39 views
-1

我遇到了我的python代码问题我一直在为我的GCSE做一个数学测验,但是我遇到了一个问题。python没有返回def段的变量

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

我的目标是让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命令?在此先感谢您的帮助。

+0

似乎你只需要与参数的顺序问题,我编辑我的回答进一步解释 – DorElias

回答

0

以及不使用该值从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) 

编辑:

以及在代码中的deepr看后,似乎你不理解范围。 看看这个Short Description of the Scoping Rules?

这个想法是,一个变量有一个“地方”,它被defiened和可以访问。当你在一个函数中定义一个变量(在def中)时,它不能从一个不同的方法自动访问。所以你的情况,例如函数正确(Q1)无法看到,因为它是在numgen定义,它不是传递给它作为参数变量answer,这是不是一个“全局”变量

编辑:

现在你的问题是参数调用它喜欢的顺序,

question(num1,num2,answer,numlist) 

但defiened像:

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

请参见区别?他们应该在同一顺序

+0

感谢您帮助如此之快,我理解了范围界定的基础知识,但您提供的链接帮助我了解了更多。我确定它会帮助我的课程^ - ^。我现在觉得愚蠢,我看到了答案GG –

0
num1, num2, answer, numlist = numgen() 

这将工作,因为你返回的东西,但让他们可以使用后你没有指派返回值什么。

这就是所谓的拆包。

它酷似

a, b = 1, 3 

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

a, b = b, a 
0

那么你需要在一些地方保存返回值:

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