def greet_user():
print('hello')
greet_user()
Hola
def greet_user(username):
print(f"hello,{
username.title()}")
greet_user('jesse')
hola, 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')
tengo un hamster
mi hamster se llama 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')
tengo un hamster
mi hamster se llama harry
Tengo un perro.
mi perro se llama 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')
yo tengo un harry
mi harry se llama 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')
Tengo un perro.
mi perro se llama Whillie
tengo un hamster
mi hamster se llama 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')
Tengo un perro.
mi perro se llama Whillie
Tengo un perro.
mi perro se llama Whillie
tengo un hamster
mi hamster se llama harry
tengo un hamster
mi hamster se llama harry
yo tengo un harry
mi harry se llama 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 HendrixJohn
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)
{'primero': 'jimi', 'último': {'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)
{'primero': 'jimi', 'último': {'hendrix'}, 'edad': 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}!")
por favor dígame su nombre:
(ingrese q en cualquier momento para salir)
Nombre: ying
Apellido: tian
¡Hola, Ying Tian!
por favor dígame su nombre:
(ingrese q en cualquier momento para salir)
Nombre:q
def greet_users(names):
for name in names:
msg=f"Hello,{
name.title()}!"
print(msg)
usernames=['hannah','ty','margot']
greet_users(usernames)
¡Hola Hannah!
¡Hola, Ty!
¡Hola, 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)
modelo de impresión: dodecaedro
modelo de impresión: colgante de robot
modelo de impresión: caja del teléfono
Se han impreso los siguientes modelos: caja del teléfono con colgante de robot
dodecaedro
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)
Modelo de impresión: dodecaedro
Modelo de impresión: colgante de robot
Modelo de impresión: carcasa del teléfono
Se han impreso los siguientes modelos: caja del teléfono con colgante de robot
dodecaedro
#禁止函数修改列表
#将列表的副本传递给函数
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)
Modelo de impresión: dodecaedro
Modelo de impresión: colgante de robot
Modelo de impresión: carcasa del teléfono
Se han impreso los siguientes modelos: caja del teléfono con colgante de robot
dodecaedro
unprinted_designs
['carcasa del teléfono', 'colgante de robot', 'dodecaedro']
#传递任意数量的实参
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')
{'ubicación': 'princetion', 'campo': 'física', 'first_name': 'albert', 'last_name': 'einstein'}