繁体   English   中英

当我尝试使用函数时,我很困惑 python 中的函数是如何工作的

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM