Python-8.2-函数-练习

练习一:编写一个名为city_province的函数
  • 它接受一个城市的名字以及该城市所属的省份
  • 这个函数应打印一个简单的句子,如Guangzhou in Guangdong Province.
  • 给用于存储省份的形参指定默认值
  • 为三个不同的城市调用这个函数,且其中至少有一个城市不属于默认省份
def city_province(city , province = 'guangdong'):
    print('\n' + str(city.title()) + " in " + 
          province.title() + " Province. ")
city_province('guangzhou')
city_province('meizhou')
city_province('xiamen' , province = 'fujian')

Guangzhou in Guangdong Province.

Meizhou in Guangdong Province.

Xiamen in Fujian Province.

练习二:编写一个名为city_province()的函数
  • 它接受城市的名称及其所属的国家
  • 至少使用三个城市-省份对调用这个函数,并打印它的返回值
  • 应返回类似这样的字符串,Guangzhou in Guangdong Province.
def city_province(city , province):
    research = "\n" + city.title() + " in " + 
    province.title() + " Province."
    return research
one_respond = city_province('guangzhou' , 'guangdong')
two_respond = city_province('meizhou' , 'guangdong')
three_respond = city_province('xiamen' , 'fujian')
print(one_respond)
print(two_respond)
print(three_respond)

Guangzhou in Guangdong Province.

Meizhou in Guangdong Province.

Xiamen in Fujian Province.

练习三:编写一个名为research(),它创建一个调查喜欢哪种水果的字典
  • 应接受被调查者的名字和喜欢的水果,并返回一个包含这两项信息的字典
  • 使用这个函数创建三个表示不同的字典,并打印每个返回的值
  • 给函数一个可选形参,年龄age
def research(full_name , favorite_fruit , age = ''):
    person = {
        'name' : full_name,
        'fruit' : favorite_fruit
    }
    if age :
        person['age'] = age
    return person
researchs = { }
one_respond = research('jack' , 'apple',20)
two_respond = research('tony' , 'banana')
three_respond = research('kevin' , 'pear')
print(one_respond)
print(two_respond)
print(three_respond)

{‘name’: ‘jack’, ‘fruit’: ‘apple’, ‘age’: 20}
{‘name’: ‘tony’, ‘fruit’: ‘banana’}
{‘name’: ‘kevin’, ‘fruit’: ‘pear’}

练习四:结合使用函数和while循环
  • 提示用户输入并将收集的信息存入到字典中
  • 询问是否继续调查,如果不是将退出循环
#version1.0
def research(full_name , favorite_fruit):
    person = {
        "name" : full_name,
        "fruit" : favorite_fruit
    }
    return person
while True :
    print("\nPlease tell me your name and your favorite fruit.")
    names = input("Enter your name : ")
    fruits = input("Enter your favorite fruit : ")
    respond = research(names , fruits)
    print(respond)
    repeat = input("Would you like to let another person respond?(yes or no)")
    if repeat == 'no' :
        break

Please tell me your name and your favorite fruit.
Enter your name : jack
Enter your favorite fruit : apple
{‘name’: ‘jack’, ‘fruit’: ‘apple’}
Would you like to let another person respond?(yes or no)yes

Please tell me your name and your favorite fruit.
Enter your name : tony
Enter your favorite fruit : banana
{‘name’: ‘tony’, ‘fruit’: ‘banana’}
Would you like to let another person respond?(yes or no)no

#version2.0,定义了一个可选形参age
def research(name , fruit ,age = ''):
    person = {
        'name' : name,
        'fruit' : fruit
    }
    if age :
        person['age'] = age
    return person
while True :
    print("\nWelcome to our survey.")
    fl_name = input("Enter your name :")
    fl_fruit = input("Enter your favorite fruit : ")
    fl_age = input("Enter your age : ")
    respond = research(fl_name , fl_fruit , fl_age)
    print(respond)
    repeat = input("Would you like to let another person respond?(yes or no)")
    if repeat == 'no' :
        break

Welcome to our survey.
Enter your name :jack
Enter your favorite fruit : apple
Enter your age :
{‘name’: ‘jack’, ‘fruit’: ‘apple’}
Would you like to let another person respond?(yes or no)yes

Welcome to our survey.
Enter your name :tony
Enter your favorite fruit : banana
Enter your age : 88
{‘name’: ‘tony’, ‘fruit’: ‘banana’, ‘age’: ‘88’}
Would you like to let another person respond?(yes or no)no

练习五:用函数打印九九乘法表
  • 调用函数打印九九乘法表
  • 利用函数的嵌套,调用函数打印九九乘法表
# version 1.0
def multiply():
    # 控制外循环,从1到9
    for o in range(1,10):
        # 内循环,每次从打一个数字开始,打印到跟行数相同的数量
        for i in range(1,o+1):
            print(o * i , end = '  ')
        print()
    return None
multiply()
print()
multiply()

1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81

1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81

# version 2.0
def printline(line_num):
    """
    line_num:代表行号
    打印一行九九乘法表
    """
    for i in range(1 , line_num + 1):
        print(line_num * i , end = "  ")
    print()
def multiply():
    for o in range(1 , 10):
        printline(o)
    return None
multiply()

1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81

练习六:传递列表
  • 创建一个包含魔术师名字的列表,并将其传递给一个名为show_magicians()的函数,这个函数打印列表中每个魔术师的名字
  • 编写一个名为make_great()的函数,对魔术师列表进行修改,在每个魔术师的名字后面都加入字样“the Great”。调用函数show_magicians(),确认魔术师列表确实改变了
  • 由于不想修改原始列表,请返回修改后的列表,并将其存储在另一个列表中
# veision1.0
def make_great(magicians , new_magicians):
    print("\nThere are new magicians: ")
    while magicians :
        magician = magicians.pop()
        print("\t" + magician.title())
        new_magicians.append(magician)
    return None
def show_magicians(magicians):
    print("There are magicians:")
    for magician in magicians:
        print("\t" + magician.title() )
    return None
magicians = ['kevin' , 'jack' , 'jake' ,'tony']
new_magicians = []
show_magicians(magicians)
make_great(magicians[:] , new_magicians)
print(magicians)
print(new_magicians)

There are magicians:
Kevin
Jack
Jake
Tony

There are new magicians:
Tony
Jake
Jack
Kevin
[‘kevin’, ‘jack’, ‘jake’, ‘tony’]
[‘tony’, ‘jake’, ‘jack’, ‘kevin’]

# version2.0
def show_magicians(magicians):
    print("There are magicians:")
    for magician in magicians:
        print("\t" + magician.title())
def make_great(magicians , new_magicians):
    print("\nThere are new magicians:")
    for magician in magicians:
        print("\t" + magician.title())
        new_magicians.append(magician)
magicians = ['kevin' , 'jack' , 'jake' , 'tony']
new_magicians = []
show_magicians(magicians)
make_great(magicians , new_magicians)
print(magicians)
print(new_magicians)

There are magicians:
Kevin
Jack
Jake
Tony

There are new magicians:
Kevin
Jack
Jake
Tony
[‘kevin’, ‘jack’, ‘jake’, ‘tony’]
[‘kevin’, ‘jack’, ‘jake’, ‘tony’]

fruits = ['apple' , 'banana']
while fruits :
    fruit = fruits.pop()
    fruits.append(fruit + "ddd")
print(fruits)
fruit = 'apple'
fruit = fruit + "d"
print(fruit)
练习七:编写一个函数,将一辆汽车的信息存储在一个字典中
  • 这个函数总是接受制造商和型号,还接受任意数量的关键字实参
  • 调用这个函数:提供必不可少的信息,以及两个名称-值对,如颜色和选装配件
    • car = make_car(‘subaru’ , ‘outback’ , color=‘blue’ , tow_package=True)
def make_car(manufacturer , version , **key_value):
    car_key_value = {}
    car_key_value['manufacturer'] = manufacturer
    car_key_value['version'] = version
    for key , value in key_value.items():
        car_key_value[key] = value
    return car_key_value
car = make_car('subaru' , 'outback' , color='blue' , tow_package=True)
print(car)    

{‘manufacturer’: ‘subaru’, ‘version’: ‘outback’, ‘color’: ‘blue’, ‘tow_package’: True}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值