从另一个函数调用函数内定义的变量而不使用全局

时间:2021-03-27 11:00:59

标签: python function loops variables return

我是 Python 的初学者,这是我的测验尝试。测验分为多个部分,我希望每个部分的分数显示在最后。

这是我的代码的简化版本。我不知道如何从另一个函数调用变量并将其放到最后,但是我不能使用全局变量或返回,因为它会阻止函数执行我的重做函数。我该怎么做?提前致谢!

5

1 个答案:

答案 0 :(得分:0)

我所知道的在函数之间传递局部作用域变量的唯一方法是使用函数参数并返回。

您的代码结构方式有点杂乱无章。尽管运行了重做的代码,但它在很多地方都运行,并且根本没有运行。

我已经重组了它。一项功能管理测验的流程。这将调用另一个提出问题并返回分数的函数。然后将其存储在分数数组中。如果他们选择重做,则再次运行部分函数并更改数组中的分数。


    def qiuzMaster():
        scores = []
        noOfSections = 5
        #I don't know how you are managing questions so this may need to be changed
        for i in range (0, noOfSections):
            scores.append(easy_questions(i)) #where i is the section number
            redo = redo()
            while redo: #since redo is boolean don't need to compare it
                print("\n")
                scores[i] = easy_questions(i) #changes the score for section i
                redo = redo()
            for i in range (0, noOfSections):
            print("You're final marks were:\nSection",i+":",scores[i] #repeats for each section
        #done with section i. moves on to i+1
        quit() #quits when done with all the above sections


    def easy_questions(sectionNumber): 

    #questions for section

           if #answer correct
                score = score + 1
                question = question + 1
                break
            else:
                print#incorrect
                question = question + 1
                break

            finalScore = str(score) + "/" + str(question)
            print("Your final mark for Section 1 is " + finalScore + ".\n")

            return finalScore

    
    def redo():

        while True:
            redo = input("Would you like to redo this section?\nEnter y/n: ")
            if redo == 'y':
                return True
            elif redo == 'n':
                return False
            else:
                print("Please enter a valid input.\n")

如果您愿意,很高兴解释我的推理或它是如何工作的。

相关问题