欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

第8章 函数 1-3 节

程序员文章站 2022-10-04 11:57:28
# 8.1 定义函数# greeter.pydef greet_user(): """显示简单的问候语 """ print("Hello!") greet_user() # 8.1.1 向函数传递信息 def greet_user(username): """显示简单的问候语""" print("H ......

# 8.1 定义函数
# greeter.py
def greet_user():
  """显示简单的问候语 """
  print("hello!")

greet_user()

# 8.1.1 向函数传递信息

def greet_user(username):
  """显示简单的问候语"""
  print("hello, " + username.title() + "!")

greet_user('star')

# 8.1.2 实参和形参
'''变量是形参,值是实参,实参是调用函数传递给函数的信息'''

 

# 8-1 消息:

def display_message():
  """显示信息"""
  print("function")

display_message()

# 8-2 喜欢的图书
def favorite_book(bookname):
  '''显示信息'''
  print("one of my favorite book is " + bookname + ".")
# 区分形参与实参,不能相同,也不能混淆
favorite_book('alice in wonderland')

 

# 8.2.1 位置实参
'''实参关联形参,基于实参顺序,称为位置实参'''
def describe_pet(animal_type, pet_name):
  '''显示宠物的信息'''
  print("\ni have a " + animal_type + ".")
  print("my " + animal_type + "'s name is " + pet_name.title() + ".")

'''实参顺序不正确,就会出现张冠李戴'''
describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')

# 8.2.2 关键字实参
def describe_pet(animal_type, pet_name):
  '''显示宠物信息'''
  print("\ni have a " + animal_type + ".")
  print("my " + animal_type + "'s name is " + pet_name.title() + ".")

'''定义关键字实参,顺序无关紧要'''
describe_pet(animal_type = 'hamster', pet_name = 'harry')
describe_pet(pet_name = 'harry', animal_type = 'hamster')

# 8.2.3 默认值
'''形参列表必须先列出没有默认值的形参,再列出有默认值的实参,正确解读位置实参。'''
def describe_pet(pet_name, animal_type = 'dog'):
  '''显示宠物信息'''
  print("\ni have a " + animal_type + ".")
  print("my " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name = 'willie')
describe_pet('willie')
describe_pet(pet_name = 'harry', animal_type = 'hamster')

# 8.2.4 等效的函数调用
'''一只名为willie的小狗'''
describe_pet(pet_name = 'willie')
describe_pet('willie')

'''一只名为harry的仓鼠'''
describe_pet('harry', 'hamster')
describe_pet(pet_name = 'harry', animal_type = 'hamster')
describe_pet(animal_type = 'hamster', pet_name = 'harry')

# 8.2.5 避免实参错误
'''提供实参或多或少不满足条件会导致不匹配错误'''

 

# 8-3 t恤
def make_shirt(shirt_size, shirt_text):
  '''显示t恤尺码及印刷文字信息'''
  print("\nmy t-shirt size is " + shirt_size + ".")
  print(shirt_text.title() + " was printed on the t-shirt" + ".")

'''双引号里加单引号强调文字的特殊性'''
make_shirt("middle", "'faith'")

# 8-4 大号t恤
def make_shirt(shirt_size, shirt_text = "'i love python'"):
  '''显示t恤尺码及印刷文字信息'''
  print("\nmy t-shirt size is " + shirt_size + ".")
  print(shirt_text + " was printed on the t-shirt" + ".")

make_shirt('large')
make_shirt('medium')
make_shirt('large', "'faith'")

# 8-5 城市
def describe_city(city_name, city_location = 'china'):
  '''显示城市名称及所在国家'''
  print("\n" + city_name.title() + " is in " + city_location.title())

describe_city('suzhou')
describe_city('nanjing')
describe_city('london','england')

 

# 8.3.1 返回简单值
def get_formatted_name(first_name, last_name):
  '''返回整洁的姓名'''
  full_name = first_name + ' ' + last_name
  return full_name.title()

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

# 8.3.2 让实参变成可选的
def get_formatted_name(first_name, middle_name, last_name):
  '''返回整洁的名字'''
  full_name = first_name + " " + middle_name + " " + last_name
  return full_name.title()

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

'''中间名变可选,设置默认空字符'''
def get_formatted_name(first_name, last_name, middle_name = ""):
  '''返回整洁的名字'''
  '''条件测试,返回函数调用行'''
  if middle_name:
    full_name = first_name + ' ' + middle_name + ' ' + last_name
  else:
    full_name = first_name + ' ' + last_name
  return full_name.title()

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

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

# 8.3.3 返回字典
def build_person(first_name, last_name):
  '''返回一个字典,其中包含有关一个人的信息'''
  person = {'first': first_name, 'last': last_name}
  return person

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

'''扩展函数'''
def build_person(first_name, last_name, age = ''):
  '''返回一个字典,其中包含有关一个人的信息'''
  person = {'first': first_name, 'last': last_name}
  if age:
  # 为字典增加 键-值
    person['age'] = age
  return person

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

# 8.3.4 结合使用函数和while循环
# ~ def get_formatted_name(first_name, last_name):
# ~ '''返回整洁的名字'''
# ~ full_name = first_name + ' ' + last_name
# ~ return full_name.title()

# ~ # 这是一个无限循环
# ~ while true:
# ~ print("\nplease tell me your name:")
# ~ f_name = input("first name: ")
# ~ l_name = input("last name: ")

# ~ formatted_name = get_formatted_name(f_name,l_name)
# ~ print("\nhello, " + formatted_name + "!")

# 使用break 退出循环
def get_formatted_name(first_name, last_name):
  '''返回整洁的名字'''
  full_name = 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("\nhello, " + formatted_name + "!")

 

# 8-6 城市名
def city_country(name, location):
  '''返回城市名车及所在地'''
  city_info = name + ' ' + location
  return city_info.title()

city = city_country('sitiago' ,'chile')
print(city)
city = city_country('suzhou', 'china')
print(city)
city = city_country('london', 'england')
print(city)

# 8-7 专辑
def make_album(singer,album):
  '''返回整洁的歌手信息'''
  person = {'singer_name': singer, 'album_name': album}
  return person

person_info = make_album('jay', '七里香')
print(person_info)
person_info = make_album('jay', '双节棍')
print(person_info)
person_info = make_album('jay', '青花瓷')
print(person_info)

# 8-8 用户的专辑
def make_album(singer,album):
  '''返回整洁的歌手信息'''
  person_info = singer + ' ' + album
  return person_info.title()

while true:
  print("\nplease tell me your favorite singer:")
  print("(enter 'q' at any time to quit)")

  singer_name = input("singer: ")
  if singer_name == 'q':
    break
  album_name = input("album: ")
  if album_name == 'q':
    break

singer_info = make_album(singer_name, album_name)
print(singer_info)