首页 > 技术文章 > 函数的练习3——python编程从入门到实践

shirley-yang 2019-07-03 20:59 原文

8-12 三明治: 编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个函数只有一个参数(它收集函数调用中提供的所有食材),并打印一条消息,对顾客点的三明治进行概述。调用这个函数三次,每次提供不同数量的实参。

def adding_foods(*foods):
    print("\nAdd following foods to your sandwich:")
    for food in foods:
        print(food)


adding_foods('corn')
adding_foods('ham', 'corn')
adding_foods('egg', 'beef', 'corn')

8-13 用户简介:复制前面的程序user_profile.py,在其中调用build_profile()来创建有关与你的简介;调用这个函数时,指定你的名和姓,以及三个描述你的键-值对。

def build_profile(first, last, **someone_info):
    profile = dict()
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in someone_info.items():
        profile[key] = value
    return profile


my_profile = build_profile('shirley', 'yang', location="xi'an", age='18', job='test')
print(my_profile)

8-14 汽车:编写一个函数,将一辆汽车的消息存储在一个字典中。这个函数总是接受制造商和型号,还接受任意数量的关键字实参。这样调用这个函数:提供必不可少的信息,以及两个名称键值对,如颜色和选装配件。这个函数必须能够像下边这样调用:


car = make_car('subaru', 'outback', color='blue', tow_package=True)


打印返回的字典,确认正确地处理了所有的信息。

def make_car(name, model, **other_info):
    car = dict()
    car['car_name'] = name
    car['car_model'] = model
    for key, value in other_info.items():
        car[key] = value
    return car


my_car = make_car('subaru', 'outback', color="blue", tow_package=True)
print(my_car)

5-15 打印模型:将示例print_models.py中的函数放在另一个名为printing_functions.py的文件中;在print_models.py的开头编写一条import语句,并修改这个文件以使用导入的函数。

printing_functions.py

def print_models(unprinted_designs, completed_models):
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print("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)
print_models.py

import printing_functions as pf

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

pf.print_models(unprinted_designs, completed_models)
pf.show_completed_models(completed_models)

8-16 导入:选择一个你编写的且只包含一个函数的程序,并将这个函数放在另一个文件中。在主程序中,使用下述各种方法导入这个函数,再调用它:


import modul_name

from modul_name import function_name

from modul_name import function_name as fn

import modul_name as mn

from modul_name import *


 

hello_xx.py

def greet_someone(name):
    message = 'Hello, ' + name.title() + '!'
    print(message)
hello_friend.py

import hello_xx
hello_xx.greet_someone("eric")

from hello_xx import greet_someone
greet_someone('lucky')

from hello_xx import greet_someone as gs
gs('babry')

import hello_xx as hx
hx.greet_someone('gre')

from hello_xx import *
greet_someone('coco')

 

推荐阅读