函數的練習3——python編程從入門到實踐


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')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM