python函数-易错知识点
定义函数:
1 def greet_users(names): #names是形参 2 """Print a simple greeting to each user in the list.""" 3 for name in names: 4 msg = "Hello, " + name.title() + "!" 5 print(msg) 6 7 usernames = ['hannah', 'ty', 'margot'] 8 greet_users(usernames)#usernames是实参
关键字def来定义一个函数。实参是调用函数时传递给函数的的信息。
调用函数时,把实参传递给函数,这个值被存储在形参中。PS:大脑中有这个概念,至于如何使用,按实际情况来考虑。
传递实参:
1 def describe_pet(pet_name, animal_type='dog'):
#关联方式:位置实参;animal_type指定了默认名。若调用函数未给形参提供实参,则使用默认名。 2 """Display information about a pet.""" 3 print("\nI have a " + animal_type + ".") 4 print("My " + animal_type + "'s name is " + pet_name.title() + ".") 5 6 # A dog named Willie. 7 describe_pet('willie') 8 describe_pet(pet_name='willie') 9 10 # A hamster named Harry. 11 describe_pet('harry', 'hamster') 12 describe_pet(pet_name='harry', animal_type='hamster')
#使用关键词实参,务必准确地指定函数定义的形参名 13 describe_pet(animal_type='hamster', pet_name='harry')
- 1.调用函数多次
- 2.位置实参的顺序很重要
返回值:
1 def get_formatted_name(first_name, last_name, middle_name=''):、
#让实参变成可选的,形参=‘空字符串’。 2 """Return a full name, neatly formatted.""" 3 if middle_name: 4 full_name = first_name + ' ' + middle_name + ' ' + last_name 5 else: 6 full_name = first_name + ' ' + last_name 7 return full_name.title() #返回 8 9 musician = get_formatted_name('jimi', 'hendrix') 10 print(musician) 11 12 musician = get_formatted_name('john', 'hooker', 'lee') 13 print(musician)
返回字典:
1 def build_person(first_name, last_name, age=''): 2 """Return a dictionary of information about a person.""" 3 person = {'first': first_name, 'last': last_name} 4 if age: 5 person['age'] = age 6 return person 7 #返回字典,将值封装到字典中 8 musician = build_person('jimi', 'hendrix', age=27) 9 print(musician)
传递列表:
将列表传递给函数后,函数能直接访问其内容。
1 def greet_users(names): 2 """Print a simple greeting to each user in the list.""" 3 for name in names: 4 msg = "Hello, " + name.title() + "!" 5 print(msg) 6 7 usernames = ['hannah', 'ty', 'margot'] #列表调用定义的函数,将列表传递给形参。 8 greet_users(usernames)
在函数中修改列表:
1 def print_models(unprinted_designs, completed_models): #定义函数1 2 """ 3 Simulate printing each design, until there are none left. 4 Move each design to completed_models after printing. 5 """ 6 while unprinted_designs: 7 current_design = unprinted_designs.pop() 8 9 # Simulate creating a 3d print from the design. 10 print("Printing model: " + current_design) 11 completed_models.append(current_design) #在函数中修改列表 12 13 def show_completed_models(completed_models): #定义函数2 14 """Show all the models that were printed.""" 15 print("\nThe following models have been printed:") 16 for completed_model in completed_models: 17 print(completed_model) 18 19 20 unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron'] 21 completed_models = [] 22 23 print_models(unprinted_designs, completed_models) 24 show_completed_models(completed_models)
导入函数:
from 模块 import 函数 as 简标记
*代表所有函数