编程语言
首页 > 编程语言> > python学习笔记-函数

python学习笔记-函数

作者:互联网

函数:传递列表

传递函数

def show_magicians(magician_names):
    for magician_name in magician_names:
        print(magician_name.title())
        
magician_names = ['tom','hanan','jay']
show_magicians(magician_names)

在函数中修改列表

将列表传递给函数后,函数就可对其进行修改。在函数中对列表的修改都是永久性的。

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

def make_great(magician_names, new_magician_names):
    while magician_names:
        current_name = 'the Great ' + magician_names.pop()
        new_magician_names.append(current_name)
    
magician_names = ['tom','hanan','jay']
new_magician_names = []
make_great(magician_names, new_magician_names)
show_magicians(new_magician_names)

禁止函数修改列表

由于在函数中修改列表是永久性的,因此需要使用切片表示法创建列表的副本,对其副本进行修改,从而保留原始列表

'''定义一个函数,打印列表中所有的元素'''
def show_magicians(magician_names):
    for magician_name in magician_names:
        print(magician_name.title())

'''修改列表中的元素'''
def make_great(magician_names, new_magician_names):
    while magician_names:
        current_name = 'the Great ' + magician_names.pop()
        new_magician_names.append(current_name)
    

magician_names = ['tom','hanan','jay']
new_magician_names = []
make_great(magician_names[:], new_magician_names)
show_magicians(magician_names)
show_magicians(new_magician_names)

调用函数时,对需要保留的原始列表做相应的处理。

标签:函数,show,python,笔记,列表,names,new,magician,name
来源: https://blog.csdn.net/tutu_nuo/article/details/115279160