Python - 从函数故障中返回变量

时间:2015-04-09 09:46:26

标签: python function variables

我目前正在学习Python并正在创建数学测验。

我创建了一个循环函数,首先创建一个随机数学和,询问答案,然后将输入与实际答案进行比较;如果一个问题是错误的,那么玩家就会失去一个点 - 反之亦然。最后计算得分,这是我尝试在函数结束时返回的内容,并在main.py文件中打印,我收到一个NameError'得分'没有定义。

我试图弄明白这一点。任何帮助/建议将不胜感激!

#generateQuestion.py

    `def generate(lives, maxNum):
        import random
        score= 0
        questionNumber = 1

        while questionNumber <=10:

                try:
                    ops = ['+', '-', '*', '/'] 
                    num1 = random.randint(0,(maxNum))
                    num2 = random.randint(0,10)
                    operation = random.choice(ops)
                    question = (str(num1) + operation + str(num2))


                    print ('Question', questionNumber)
                    print (question)
                    maths = eval(str(num1) + operation + str(num2))
                    answer=float(input("What is the answer? "))

                except ValueError:
                    print ('Please enter a number.')
                    continue

                if answer == maths:
                    print ('Correct')
                    score = score + 1
                    questionNumber = questionNumber + 1
                    print ('Score:', score)
                    print ('Lives:', lives)
                    print('\n')
                    continue

                elif lives == 1:
                    print ('You died!')
                    print('\n')
                    break

                else:
                    print ('Wrong answer. The answer was actually', maths)
                    lives = lives - 1
                    questionNumber = questionNumber + 1
                    print ('Score:', score)
                    print ('Lives:', lives)
                    print('\n')
                    continue

        if questionNumber == 0:
            print ('All done!')
            return score       
        `

我的主要文件

#main.py
        import random
        from generateQuestion import generate


        #Welcome message and name input.
        print ('Welcome, yes! This is maths!')
        name = input("What is your name: ")
        print("Hello there",name,"!" )
        print('\n')

        #difficulty prompt
        while True:

        #if input is not 1, 2 or 3, re-prompts.
            try:
                difficulty = int (input(' Enter difficulty (1. Easy, 2. Medium, 3. Hard): '))       
            except ValueError:
                print ('Please enter a number between 1 to 3.')
                continue
            if difficulty < 4:
                break
            else:
                print ('Between 1-3 please.')

        #if correct number is inputted (1, 2 or 3).
        if difficulty == 1:
            print ('You chose Easy')
            lives = int(3)
            maxNum = int(10)


        if difficulty == 2:
            print ('You chose Medium')
            lives = int(2)
            maxNum = int(25)


        if difficulty == 3:
            print ('You chose Hard')
            lives = int(1)
            maxNum = int(50)

        print ('You have a life count of', lives)
        print('\n')

        #generateQuestion
        print ('Please answer: ')
        generate(lives, maxNum)

        print (score) 
        #not printing^^

        '

我尝试了一种不同的方法,只使用了函数文件(没有main),并将其缩小到了返回得分变量的问题,这段代码是:

def generate(lives, maxNum):
    import random
    questionNumber = 1
    score= 0
    lives= 0
    maxNum= 10

    #evalualates question to find answer (maths = answer)
    while questionNumber <=10:

            try:
                ops = ['+', '-', '*', '/'] 
                num1 = random.randint(0,(maxNum))
                num2 = random.randint(0,10)
                operation = random.choice(ops)
                question = (str(num1) + operation + str(num2))


                print ('Question', questionNumber)
                print (question)
                maths = eval(str(num1) + operation + str(num2))
                answer=float(input("What is the answer? "))

            except ValueError:
                print ('Please enter a number.')
                continue

            if answer == maths:
                print ('Correct')
                score = score + 1
                questionNumber = questionNumber + 1
                print ('Score:', score)
                print ('Lives:', lives)
                print('\n')
                continue

            elif lives == 1:
                print ('You died!')
                print('\n')
                break

            else:
                print ('Wrong answer. The answer was actually', maths)
                lives = lives - 1
                questionNumber = questionNumber + 1
                print ('Score:', score)
                print ('Lives:', lives)
                print('\n')
                continue

    if questionNumber == 0:
        return score


def scoreCount():
    generate(score)
    print (score)


scoreCount()

2 个答案:

答案 0 :(得分:3)

我认为问题出在主要的最后一行:

print ('Please answer: ')
generate(lives, maxNum)
print ('score')

您没有收到返回的值。它应该改为:

print ('Please answer: ')
score = generate(lives, maxNum) #not generate(lives, maxNum)
print (score)  # not print('score')

这样可行。

答案 1 :(得分:0)

它的工作方式不是:

def a():
    score = 3
    return score
def b():
    a()
    print(score)

(并且print('score')只会打印单词'score'。)

它的工作原理如下:

def a():
    score = 3
    return score

def b():
    print(a())