簡體   English   中英

python - 從另一個函數更改函數中的變量

[英]python - changing a variable in a function from another function

函數 user_message 有沒有辦法從其原始函數外部更改變量 user_variable?

def user_value():
    user_variable = 0
    while user_variable < 1:
        user_variable = int(input("Please enter a value: "))

def user_message():
    user_message = int(input("Please enter a number: "))
    user_value()
    user_variable = user_variable + user_message

user_message()
print(user_variable)

不太確定你想從印刷品中得到什么,但我玩過它並想出了這個解決方案:

def user_value(user_variable=0):
    while user_variable > 1:
        input_variable = int(input("Please enter a value: "))
        user_variable += input_variable
        print("New value: " + str(user_variable))


def user_message():
    user_message = int(input("Please enter a number: "))
    user_value(user_message)


print(user_message())

這是您將使用return語句將某些內容返回給調用者的地方。 您將返回user_variable並將其作為參數傳遞給您要在其中使用它的函數。這是一個示例:

def foo():
    x = 10
    return x

def bar(x):
    # do stuff

函數中聲明的變量和函數參數是局部變量,這意味着它們只存在於函數范圍內。 Python 中的范圍塊由縮進級別決定。 函數簽名( def func_name(): )下的任何內容和 4 個縮進空格都是該函數本地范圍的一部分。

# global scope

def foo():
    # foo’s local scope here

# global scope

暫無
暫無

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

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