[英]im confused how functions work in python when im trying to use them
所以代碼是
magician_names = ['Elon musk', 'Neuralink', 'Neuralink']
def show_magicians(names):
print("each object/person in the list:\n")
for name in names:
print(name.title())
def make_great(list):
for q in list:
q = 'the Great ' + q.title()
make_great(magician_names)
print(magician_names)
您只是重新分配循環變量q
,而不是實際改變列表:
def make_great(list):
for q in list:
q = 'the Great ' + q.title()
# q is now a different new str object, but list is unchanged
改為:
def make_great(lst): # also do not shadow the built-in list
for i in range(len(lst)):
lst[i] = 'the Great ' + lst[i].title()
上面的答案也是正確的,你沒有改變列表我會嘗試澄清一些事情讓我們看看發生了什么看評論
magician_names = ['Elon musk', 'Neuralink', 'Neuralink'] #declared a list
def show_magicians(names): #defined a function though never called
print("each object/person in the list:\n")
for name in names:
print(name.title())
def make_great(list): # defined a function
for q in list: #iterated on list
q = 'the Great ' + q.title() # stored a result into memory never used or printed it or returned anything
make_great(magician_names) #called the function operated on list never printed it but it worked in memory
print(magician_names)
簡單來說,如果你在房間里有 Dog Maxi(假設一個函數),除非你打電話給Maxi,否則它不會來找你。 但是 Maxi 將留在房間show_magicians這里。 你打電話給 Maxi,讓他默默地說 woof woof,所以你從來沒有聽到他的聲音,但 Maxi 說並做了他的工作(就像這里沒有打印聲明一樣)。
嘗試放入現實世界的類比希望有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.