簡體   English   中英

將信息從一個 function 傳遞到另一個時遇到問題 (Python)

[英]Having problems passing info from one function to another (Python)

我對 python 還很陌生(已經上了幾個月的課),我遇到了一個反復出現的問題,我的代碼涉及傳遞信息,例如 integer,從一個 function 到另一個。 在這種情況下,我在將“totalPints”從“def getTotal”傳遞到“def averagePints”時遇到了問題(def averagePints 中的 totalPints 默認為 0)。

def main():
    endQuery = "n"

    while endQuery == "n":
        pints = [0] * 7
        totalPints = 0
        avgPints = 0
        option = ""

        print("Welcome to the American Red Cross blood drive database.")
        print()
        print("Please enter 'w' to write new data to the file. Enter 'r' to read data currently on file. Enter 'e' to "
              "end the program.")

        try:
            option = input("Enter w/r/e: ")
        except ValueError:
            print()
            print("Please input only w/r/e")

        if option == "w":
            print()

            def getPints(pints):
                index = 0
                while index < 7:
                    pints[index] = input("Input number of Pints of Blood donated for day " + str(index + 1) + ": ")
                    print(pints)
                    index = index + 1

            getPints(pints)

            def getTotal(pints, totalPints):
                index = 0
                while index < 7:
                    totalPints = totalPints + int(pints[index])
                    index = index + 1
                print(totalPints)

            getTotal(pints, totalPints)

            def averagePints(totalPints, avgPints):
                avgPints = float(totalPints) / 7
                print(avgPints)

            averagePints(totalPints, avgPints)

將信息從“def getPints”傳遞到“def getTotal”工作正常,並且都打印出准確的信息,但沒有從“def getTotal”傳遞到“def averagePints”並返回 0。在這種情況下我做錯了什么? 是不是和上面列出的變量的scope有關?

這是我第一次在 Stack Overflow 上發帖,因為我可以找到任何解決我遇到的問題的方法。 我希望從這段代碼中發生的事情是將“def getTotal”中的“totalPints”中的數字傳遞給“def averagePints”以使用該數字進行計算。 我試着搞亂聲明變量的范圍和調用函數的順序,但我仍然無法真正說出我遺漏了什么。 我所知道的是“def averagePints”中“totalPints”的值總是返回 0。

您有一個可變范圍問題。 在 getTotal 中,totalPints 正在更新為 function 的本地值,而不是您期望的全局值。 從 function 返回新值並分配它似乎具有預期的效果。 以下是更新后的代碼段:

            def getTotal(pints, totalPints):
                index = 0
                while index < 7:
                    totalPints = totalPints + int(pints[index])
                    index = index + 1
                print(totalPints)
                return totalPints

            totalPints = getTotal(pints, totalPints)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM