Python - 从函数故障返回变量



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

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

我一直在努力解决这个问题

。任何帮助/建议将不胜感激!

#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()

我认为问题出在main的最后几行:

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

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

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

这将起作用。

它的工作方式不是:

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

print('score')将简单地打印单词'score'

它的工作原理是这样的:

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

最新更新