当我试图使用python函数时,我很困惑它们是如何工作的
所以代码是当我试图使用python函数时,我很困惑它们是如何工作的,python,Python,所以代码是 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 Gr
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)
简单地说,如果你的房间里有狗Maxi(假设有一个函数),除非你打电话给它,否则它不会来找你。但马克西将留在这里表演魔术师。你打电话给Maxi,让他安静地说woof woof,这样你就再也听不到他的声音了,但是Maxi说了,做了他的工作(这里没有打印声明)
试着在现实世界中进行类比,希望能有所帮助你对哪一部分有困难?问题是什么?当我打印(魔术师的名字)时,我应该得到列表中每个项目之间的伟大的输出