《Python编程从入门到实践》学习笔记08函数

def greet_user():
    print('hello')
    
greet_user()

hello

def greet_user(username):
    print(f"hello,{username.title()}")
greet_user('jesse')

hello,Jesse

#传递实参
def describe_pet(animal_type,pet_name):
    #显示宠物信息
    print(f'\nI have a {animal_type}.')
    print(f"my {animal_type}'s name is {pet_name.title()}")
    
describe_pet('hamster','harry')

I have a hamster.
my hamster’s name is Harry

def describe_pet(animal_type,pet_name):
    #显示宠物信息
    print(f'\nI have a {animal_type}.')
    print(f"my {animal_type}'s name is {pet_name.title()}")
    
describe_pet('hamster','harry')
describe_pet('dog','whillie')

I have a hamster.
my hamster’s name is Harry

I have a dog.
my dog’s name is Whillie

def describe_pet(animal_type,pet_name):
    #显示宠物信息
    print(f'\nI have a {animal_type}.')
    print(f"my {animal_type}'s name is {pet_name.title()}")
    
describe_pet(pet_name='hamster',animal_type='harry')

I have a harry.
my harry’s name is Hamster

def describe_pet(pet_name,animal_type='dog'):
    #显示宠物信息
    print(f'\nI have a {animal_type}.')
    print(f"my {animal_type}'s name is {pet_name.title()}")
    
describe_pet('whillie')
describe_pet('harry','hamster')

I have a dog.
my dog’s name is Whillie

I have a hamster.
my hamster’s name is Harry

def describe_pet(pet_name,animal_type='dog'):
    #显示宠物信息
    print(f'\nI have a {animal_type}.')
    print(f"my {animal_type}'s name is {pet_name.title()}")
    
describe_pet('whillie')
describe_pet(pet_name='whillie')

describe_pet('harry','hamster')
describe_pet(pet_name='harry',animal_type='hamster')
describe_pet(pet_name='hamster',animal_type='harry')

I have a dog.
my dog’s name is Whillie

I have a dog.
my dog’s name is Whillie

I have a hamster.
my hamster’s name is Harry

I have a hamster.
my hamster’s name is Harry

I have a harry.
my harry’s name is Hamster

def get_formatted_name(first_name,last_name):
    full_name=f"{first_name} {last_name}"
    return full_name.title()

musician=get_formatted_name('jimi','hendrix')
print(musician)

Jimi Hendrix

def get_formatted_name(first_name,middle_name,last_name):
    full_name=f"{first_name} {middle_name} {last_name}"
    return full_name.title()
musician=get_formatted_name('john','lee','hooker')
print(musician)

John Lee Hooker

def get_formatted_name(first_name,last_name,middle_name=''):
    if middle_name:
        full_name=f"{first_name} {middle_name} {last_name}"
    else:
        full_name=f"{first_name} {last_name}"
    return full_name.title()

musician=get_formatted_name('jimi','hendrix')
print(musician)

musician=get_formatted_name('john','lee','hooker')
print(musician)

Jimi Hendrix
John Hooker Lee

def build_person(first_name,last_name):
    person={'first':first_name,'last':{last_name}}
    return person

musician=build_person('jimi','hendrix')
print(musician)

{‘first’: ‘jimi’, ‘last’: {‘hendrix’}}

def build_person(first_name,last_name,age=None):
    person={'first':first_name,'last':{last_name}}
    if age:
        person['age']=age
    return person

musician=build_person('jimi','hendrix',27)
print(musician)

{‘first’: ‘jimi’, ‘last’: {‘hendrix’}, ‘age’: 27}

def get_formatted_name(first_name,last_name):
    full_name=f"{first_name} {last_name}"
    return full_name.title()

while True:
    print('\nplease tell me your name:')
    print('(enter q at any time to quit)')
    
    f_name=input("First name:")
    if f_name=='q':
        break
        
    l_name=input('Last name:')
    if l_name=='q':
        break
        
    formatted_name=get_formatted_name(f_name,l_name)
    print(f"\nHello,{formatted_name}!")

please tell me your name:
(enter q at any time to quit)
First name:ying
Last name:tian

Hello,Ying Tian!

please tell me your name:
(enter q at any time to quit)
First name:q

def greet_users(names):
    for name in names:
        msg=f"Hello,{name.title()}!"
        print(msg)
        
usernames=['hannah','ty','margot']
greet_users(usernames)

Hello,Hannah!
Hello,Ty!
Hello,Margot!

unprinted_designs=['phone case','robot pendant','dodecahedron']
completed_models=[]

while unprinted_designs:
    current_design=unprinted_designs.pop()
    print(f"printing model:{current_design}")
    completed_models.append(current_design)
    
print('\nthe following models have been printed:')
for completed_model in completed_models:
    print(completed_model)

printing model:dodecahedron
printing model:robot pendant
printing model:phone case

the following models have been printed:
dodecahedron
robot pendant
phone case

def print_models(unprinted_designs,completed_models):
     while unprinted_designs:
            current_design=unprinted_designs.pop()
            print(f"Printing model:{current_design}")
            completed_models.append(current_design)
            
def show_completed_models(completed_models):
    print('\nthe following models have been printed:')
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs=['phone case','robot pendant','dodecahedron']
completed_models=[]

print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)

Printing model:dodecahedron
Printing model:robot pendant
Printing model:phone case

the following models have been printed:
dodecahedron
robot pendant
phone case

#禁止函数修改列表
#将列表的副本传递给函数
function_name(list_name[:])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_29540\3954775793.py in <module>
      1 #将列表的副本传递给函数
----> 2 function_name(list_name[:])

NameError: name 'function_name' is not defined
def print_models(unprinted_designs,completed_models):
     while unprinted_designs:
            current_design=unprinted_designs.pop()
            print(f"Printing model:{current_design}")
            completed_models.append(current_design)
            
def show_completed_models(completed_models):
    print('\nthe following models have been printed:')
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs=['phone case','robot pendant','dodecahedron']
completed_models=[]

print_models(unprinted_designs[:],completed_models)
show_completed_models(completed_models)

Printing model:dodecahedron
Printing model:robot pendant
Printing model:phone case

the following models have been printed:
dodecahedron
robot pendant
phone case

unprinted_designs

[‘phone case’, ‘robot pendant’, ‘dodecahedron’]

#传递任意数量的实参
def make_pizza(toppings):
    print(toppings)
    
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
pepperoni
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_29540\182964292.py in <module>
      3 
      4 make_pizza('pepperoni')
----> 5 make_pizza('mushrooms','green peppers','extra cheese')

TypeError: make_pizza() takes 1 positional argument but 3 were given
#形参名*toppings中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中
def make_pizza(*toppings):
    print(toppings)
    
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')
def make_pizza(size,*toppings):
    print(f"\nMaking a {size}-inch pizza with the following toppings:")
    for topping in toppings:
        print(f"-{topping}")
              
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')
Making a 16-inch pizza with the following toppings:
-pepperoni

Making a 12-inch pizza with the following toppings:
-mushrooms
-green peppers
-extra cheese
#使用任意数量的关键字实参
def build_profile(first,last,**user_info):
    user_info['first_name']=first
    user_info['last_name']=last
    return user_info

user_profile=build_profile('albert','einstein',location='princetion',field='physics')

{‘location’: ‘princetion’, ‘field’: ‘physics’, ‘first_name’: ‘albert’, ‘last_name’: ‘einstein’}

你可能感兴趣的:(python,python,笔记,开发语言)