我目前正在阅读埃里克·马特思的Python速成班,我很难理解第8章,第8章都是关于函数的。我被困在练习8-10中,它要求我使用一个新的函数来更改上一次练习中使用的列表。
下面是练习:
8-9. Magicians: Make a list of magician's names. Pass the list to a function called show_magicians(), which prints the name of each magician in the list.
8-10. Great Magicians: Start with a copy of your program from exercise 8-9. Write a function make_great() that modifies the list of magicians by adding the phrase the great to each magician's name. Call show_magicians() to see that the list has actually been modified.这里是我8-9:的代码
def show_magicians(names):
"""Print each magician name"""
for name in names:
msg = name.title()
print(msg)
magician_names = ['sonic', 'tails', 'knuckles']
show_magicians(magician_names)我在这个网站上看到了一个非常相似的话题,所以我尝试使用这个页面第一个答案中的代码来帮助我:Python crash course 8-10
然而,我的代码似乎仍然是不正确的,因为编译器在每个名称之后打印3次“伟大”。
这里是我为8-10使用的当前代码
def show_magicians(names):
"""Print each magician name"""
for name in names:
msg = name.title()
print(msg)
magician_names = ['sonic', 'tails', 'knuckles']
show_magicians(magician_names)
def make_great(list_magicians):
"""Add 'Great' to each name."""
for magician_name in magician_names:
for i in range(len(list_magicians)):
list_magicians[i] += " the great!"
make_great(magician_names)
show_magicians(magician_names)我不知道为什么,但似乎我一直在努力完成这一章的功能。有没有人会有推荐的教程来帮助我更好地理解函数?谢谢您抽时间见我。
发布于 2016-09-11 22:31:34
好的,你在外面有一个额外的循环,去掉它。最后代码:
def show_magicians(names):
"""Print each magician name"""
for name in names:
msg = name.title()
print(msg)
magician_names = ['sonic', 'tails', 'knuckles']
show_magicians(magician_names)
def make_great(list_magicians):
"""Add 'Great' to each name."""
for index, item in enumerate(list_magicians):
list_magicians[index] += " the great!"
make_great(magician_names)
show_magicians(magician_names)你在做for-in和for-in range。这使得代码重复了字符串的追加。让我解释一下你之前的计划:
解释:在每次迭代中,都会使用for-in循环,使其循环内环3次。因此,外部循环每迭代一次,它会重复内部循环3次,使其在每个名称中追加3次the great。
此外,作为链接问题的答案,我宁愿您使用enumerate而不是range(len(list_magicians))。
发布于 2016-09-11 22:34:27
将第二种方法更改为:
def make_great(list_magicians):
"""Add 'Great' to each name."""
i = 0
for magician_name in magician_names:
list_magicians[i] += " the great!"
i += 1目前,您正在使用两个for loops循环两次,导致添加了3次!
发布于 2016-09-11 22:36:07
让我们看看您的make_great函数:
def make_great(list_magicians):
"""Add 'Great' to each name."""
for magician_name in magician_names:
for i in range(len(list_magicians)):
list_magicians[i] += " the great!"这是干什么用的?
for magician_name in magician_names:通过magician_names循环。
for i in range(len(list_magicians)):按索引遍历list_magicians。
list_magicians[i] += " the great!"将the great!添加到list_magicians的ith元素中。
没有必要使用哪一行代码?
for magician_name in magician_names:循环通过这是没有用的。因为它的长度是3,所以在每个元素中添加了3个the great!。删除这一行代码,函数就会正常工作。
https://stackoverflow.com/questions/39441236
复制相似问题