第8章 函數 4-8節

来源:https://www.cnblogs.com/sunstar/archive/2020/01/12/12184920.html
-Advertisement-
Play Games

# 8.4.1 在函數中修改列表def greet_user(names): '''向列表中的每位用戶都發出簡單的問候''' for name in names: msg = "Hello, " + name.title() + "!" print(msg) usernames = ['star', ...


# 8.4.1 在函數中修改列表
def greet_user(names):
  '''向列表中的每位用戶都發出簡單的問候'''
  for name in names:
    msg = "Hello, " + name.title() + "!"
    print(msg)

usernames = ['star','james','wendy']
greet_user(usernames)

# 不使用函數修改列表
# 首先創建一個列表,其中要包含一些列印的設計
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []

# 模擬列印每個設計,直到沒有未列印的設計為止
# 列印每個設計後,都將其移到列表completed_models中
while unprinted_designs:
  current_design = unprinted_designs.pop()

  # 模擬根據設計製作3D列印模型的過程
  print("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)

# 使用函數修改列表
def print_models(unprinted_designs, completed_models):
  '''
  模擬列印每個設計,直到沒有未列印的設計為止
  列印每個設計後,都將其移到列表completed中
  '''
  while unprinted_designs:
    current_design = unprinted_designs.pop()

# 模擬根據設計製作3D列印模型的過程
print("Printing model: " + current_design)
completed_models.append(current_design)

def show_completed_models(completed_models):
  '''顯示列印好的所有模型'''
  print("\nThe following models hvae been printed:")
  for completed_model in completed_models:
    print(completed_model)

unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)

# 8.4.2 禁止函數修改列表——function_name(lsit_name[:]),切片表示法[:]創建列表的副本
def print_models(unprinted_designs, completed_models):
  '''
  模擬列印每個設計,直到沒有未列印的設計為止
  列印每個設計後,都將其移到列表completed中
  '''
  while unprinted_designs:
    current_design = unprinted_designs.pop()

# 模擬根據設計製作3D列印模型的過程
print("Printing model: " + current_design)
completed_models.append(current_design)

def show_completed_models(completed_models):
  '''顯示列印好的所有模型'''
  print("\nThe following models hvae been printed:")
  for completed_model in completed_models:
    print(completed_model)

unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs[:], completed_models)
show_completed_models(completed_models)

 

# 8-9 魔術師
def show_magicians(names):
  '''呈現列表中的名字'''
  for name in names:
  msg = "Welcome international magician, " + name.title() + "!"
  print(msg)

usernames = ['james','wendy','star']
show_magicians(usernames)

# 8-10 了不起的魔術師
def show_magicians(list_name, modify_infor):
  '''
  修改列表中的每個信息,直到修改完成
  修改後的信息,都將其移到modify_infor中
  '''
while list_name:
  current_names = list_name.pop()
# 修改信息的過程
  print("\nModify information: " + current_names)
  modify_infor.append(current_names)

def make_great(modify_info):
  '''顯示修改好的信息'''
  print("\nThe following information have benn modified:")
  for modify_info in modify_infor:
    print("The great magician is " + modify_info)

list_name = ['james','star','wendy']
modify_infor = []

show_magicians(list_name,modify_infor)
make_great(modify_infor)
print(list_name) # 原列表信息已經徹底變空

# 8-11 不變的魔術師
def show_magicians(list_name, modify_infor):
  '''
  修改列表中的每個信息,直到修改完成
  修改後的信息,都將其移到modify_infor中
  '''
  while list_name:
    current_names = list_name.pop()

# 修改信息的過程
  print("\nModify information: " + current_names)
  modify_infor.append(current_names)

def make_great(modify_info):
  '''顯示修改好的信息'''
  print("\nThe following information have benn modified:")
  for modify_info in modify_infor:
    print("The great magician is " + modify_info)

list_name = ['james','star','wendy']
modify_infor = []

show_magicians(list_name[:],modify_infor)
make_great(modify_infor)
print(list_name) # 原列表信息沒有改變

 

# 任意數量實參
def make_pizza(*toppings):
  '''列印顧客點的所有配料'''
  print(toppings)

make_pizza('pepperoni')
make_pizza('msshrooms','green peppers','extra cheese')

# 8.5.1 結合使用位置實參和任意數量實參
def make_pizza(size, *toppings):
'''概述要製作的披薩'''
  print("\nMaking a " + str(size) +
  "-inch pizza with the following toppings:")
  for topping in toppings:
    print("- " + topping)

make_pizza(16,'pepperoni')
make_pizza(12,'msshrooms','green peppers','extra cheese')

# 8.5.2 使用任意數量的關鍵字實參
def build_profile(first, last, **user_info): # 總是接受名和姓,還接受任意數量的關鍵字實參
  '''創建一個字典,其中包含我們知道的有關於用戶的一切信息'''
  profile = {}
  profile['first_name'] = first # 匹配鍵-值對
  profile['last_name'] = last # 匹配鍵-值對
  for key, value in user_info.items():
    profile[key]=value # 定義profile鍵_值對
  return profile

user_profile = build_profile('albert','einstin',
             location='princeton',
             filed='pyhsics')
print(user_profile)


# 8-12 三明治
def make_sandwich(*toppings):
  '''列印客戶要點的材料'''
  print(toppings)

make_sandwich('tomato')
make_sandwich('cheese', 'meat', 'boun')

# 8-13 用戶簡介:
def build_profile(first, last, **user_info): # 兩個星號表示可容納任意數量的空字典
  '''創建一個空字典,包含我有關的個人信息'''
  profile = {}
  profile['first_name'] = first
  profile['last_name'] = last
  for key, value in user_info.items():
    profile[key] = value
  return profile

user_profile = build_profile('sun','star',
             location='suzhou',
             age='27',
             filed='planning')
print(user_profile)

# 8-14 汽車
def build_profile(first, last, **car_info):
  '''創建一個空字典,包含我們知道的有關車的信息'''
  profile = {}
  profile['manufacturer:'] = first
  profile['model:'] = last
  for key, value in car_info.items():
    profile[key] = value
  return profile

car_profile = build_profile('sabaru','outback',
            color='bule',
            two_package=True)
print(car_profile)

 

# 8.6.1 導入整個模塊
'''子文件需要新建_init_.py空文件'''
from Function_library import pizza

'''模塊名稱pizza和函數名make_pizza(),並用句點分隔它們'''
pizza.make_pizza(16,'peppertoni')
pizza.make_pizza(12,'mushrooms', 'green peppers', 'extra cheese')

# 8.6.2 導入特定函數
'''from Function_library.pizza import:導入特定函數'''
from Function_library.pizza import make_pizza
'''顯式地導入函數make_pizza(),無須句點分隔,只需指定名稱'''
make_pizza(16,'peppertoni')
make_pizza(12,'mushrooms', 'green peppers', 'extra cheese')

# 8.6.4 使用as給模塊指定別名
'''from Function_library.pizza import make_=pizza as mp: 指定別名語法'''
from Function_library.pizza import make_pizza as mp

'''無須複雜輸入make_pizza,只需輸入mp即可'''
mp(16,'peppertoni')
mp(12,'mushrooms', 'green peppers', 'extra cheese')

# 8.6.5 導入模塊中的所有函數
'''使用(*)號運算符可讓python導入模塊中的所有函數:'''
from Function_library.pizza import *

make_pizza(16,'peppertoni')
make_pizza(12,'mushrooms', 'green peppers', 'extra cheese')

# 指定函數描述性名稱幫助你和別人明白代碼
# 每個函數都有包含簡要地闡述其功能的註釋,緊跟函數定義後面


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、二分法查找 1.二分法查找是建立在已經排序的基礎之上的 2.程式分析是從下到大​排序。 3.這個數組中沒有重覆的元素​。 package com.bjpowernode.java_learning; ​ public class D71_1_ { public static void main( ...
  • 在初學Java的時候,經常能看到教材上的寫法,使用了介面Map來引用一個map,而不是它的具體實現,那麼這樣做的好處是什麼呢? <Effective Java>第52條:通過介面引用對象 作者認為,如果有合適的介面類型存在,那麼對於參數、返回值、變數和域來說,就都應該使用就介面類型進行聲明。 只有當 ...
  • 背景 有處理過生產問題的同學基本都能遇到系統忽然緩慢,CPU突然飆升,甚至整個應用請求不可用。當出現這種情況下,在不影響數據準確性的前提下,我們應該儘快導出jstack和記憶體信息,然後重啟系統,儘快回覆系統的可用性,避免用戶體驗過差。本文針對CPU飆升問題,提供該問題的排查思路,從而能夠快速定位到某 ...
  • 1、性能 對值類型使用非泛型集合類,在把值類型轉換為引用類型,和把引用類型轉換為值類型時,需要進行裝箱和拆箱操作。裝箱和拆箱的操作很容易實現,但是性能損失較大。假如使用泛型,就可以避免裝箱和拆箱操作。 1 ArrayList list=new ArrayList(); 2 list.Add(20); ...
  • 兩段閑話,費曼學習方法是【重點】 當你邁出第一步,就不要收回來,邁步了感到涼,不行我要回到起點重新選擇那還是會退回來的,所以一定要走下去,一步一步都下去,終會走到頂點,就如人類的知識之海是一個園,出生那一刻我們站在了圓點,不後退不轉彎不轉圈的走下去是一條直線,終會走到圓的邊上,成為一個方向的頂尖,甚 ...
  • 開源代碼更新至1.3版本,1.3版本後thunder模塊已經不能下載了(種子和磁力鏈不能下載,http鏈接可以正常下載),所以1.3版本之後就沒再維護代碼了,現在把1.3版本源碼也開源出來。 我也不知道為什麼不能下載了,因為thunder也是別人的開源項目。我並有去深入研究這個模塊。 ...
  • IYUU自動輔種工具,目前能對國內大部分的PT站點自動輔種PT種子、BT種子;同時,附帶的下載模塊可訂閱各站免費種。支持下載器集群,支持多盤位,支持多下載目錄,支持遠程連接等。 1.群暉、威聯通不裝軟體,添加免費種子到transmission、qBittorrent,支持微信通知、郵件通知,支持自定... ...
  • 樹莓派智能小車,實現功能:基於超聲波和紅外的自動避障、樹莓派端向PC端的實時圖像傳輸、基於視覺的車道線循跡、基於Tensorflow Object Detection的目標檢測、基於視覺的網球追蹤。 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...