簡體   English   中英

使用 function (Python) 之外的變量

[英]Using a variable outside of the function (Python)

所以我又開始學習 python 並且我目前正在制作一個迷你電影推薦器。 我希望我的代碼更易於理解,所以我總是嘗試使用 def 來簡化代碼。 我的問題是;

def welcome():
    print("""Welcome to the low budget film recommender!
             Here you can tell me what kind of movies do you like or what movie did you watch
             and I'll suggest you a movie from my database according to that.""")
    name = input("But first I need to learn your name:>> ").capitalize()
    print(f"Nice to meet you {name}")
    return name

我想在函數外部使用名稱變量(實際上在另一個 function 內部)但它給了我 NameError 並說“名稱”未定義。 如何解決此問題並在 function 之外使用名稱變量?

將其聲明為全局變量並不是最佳實踐(正如其他答案所建議的那樣)。

您應該將 go 放在調用welcome() 的任何位置,並使用結果設置一個變量(您在welcome 中返回):

name = welcome()
print(f"This is the result of welcome: {name}")

我對您的代碼進行了一些修改,通過使用 name 變量作為全局變量,您可以實現您想要的。 看看代碼

#name as a global variable 
name = input("But first I need to learn your name:>> ").capitalize()

def welcome():
    print("""Welcome to the low budget film recommender!
             Here you can tell me what kind of movies do you like or what movie did you watch
             and I'll suggest you a movie from my database according to that.""")
    # name = input("But first I need to learn your name:>> ").capitalize()
    print(f"Nice to meet you {name}")
    return name

print(welcome())

def message():
    return name

print(message())

如果您還需要任何幫助,請告訴我

您可以將變量name聲明為全局變量。

代碼 -

def welcome():
    global name
    print("""Welcome to the low budget film recommender!
             Here you can tell me what kind of movies do you like or what movie did you watch
             and I'll suggest you a movie from my database according to that.""")
    name = input("But first I need to learn your name:>> ").capitalize()
    print(f"Nice to meet you {name}")
    return name


def second_function():
    welcome()
    print(name) #prints the value of name in this function which was defined in the welcome()

second_function()

暫無
暫無

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

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