Python编程-从入门到实战(习题8-[9-11])

8-9 魔术师:创建一个包含魔术师名字的列表,并将其传递给一个名为show_magicians()的函数,这个函数打印列表中每个魔术师的名字。

def show_magicians(magician_names):
    for magician_name in magician_names:
        print(magician_name.title())

magician_names = ['wolf','wolf01','heaa']

show_magicians(magician_names)

8-10 了不起的魔术师: 在你为完成练习 8-9 而编写的程序中,编写一个名为make_great() 的函数,对魔术师列表进行修改,在每个魔术师的名字中都加入字样“theGreat”。调用函数 show_magicians() ,确认魔术师列表确实变了。

方法一:
def show_magicians(magician_names):
    for magician_name in magician_names:
        print(magician_name.title())

def make_great(magician_names):
    for index,magician_name  in enumerate(magician_names):
        magician_names[index] = "The Great " + magician_name.title()

magician_names = ['wolf','wolf01','heaa']

make_great(magician_names)
show_magicians(magician_names)
方法二:
def show_magicians(magician_name_full):
    for magician_name in magician_name_full:
        print(magician_name.title())

def make_great(magician_names,magician_name_full):
    while magician_names:
        current_magician_name = magician_names.pop()
        magician_name_full.append("The Great " + current_magician_name)

magician_names = ['wolf', 'wolf01', 'heaa']
magician_name_full = []

make_great(magician_names,magician_name_full)
show_magicians(magician_name_full)

8-11 不变的魔术师:修改你为完成练习 8-10 而编写的程序,在调用函数make_great()时,向它传递魔术师列表的副本。由于不想修改原始列表,请返回修改后的列表,并将其存储到另一个列表中。分别使用这两个列表来调用 show_magicians(),确认一个列表包含的是原来的魔术师名字,而另一个列表包含的是添加了字样“theGreat”的魔术师名字。

def show_magicians(magician_name_full):
    for magician_name in magician_name_full:
        print(magician_name.title())

def make_great(magician_names,magician_name_full):
    while magician_names:
        current_magician_name = magician_names.pop()
        magician_name_full.append("The Great " + current_magician_name)

magician_names = ['wolf', 'wolf01', 'heaa']
magician_name_full = []

make_great(magician_names[:],magician_name_full)
show_magicians(magician_name_full)
print(magician_names)

你可能感兴趣的:(Python)