Python基礎(chǔ)語(yǔ)法 - 2 Python函數(shù)與模塊

1 函數(shù)定義傳參
2 模塊和包
3 標(biāo)準(zhǔn)包和第三方包和虛擬環(huán)境
4 高階函數(shù) map filter reduce
5 文件讀寫和json和pickle

1 函數(shù)的定義和實(shí)現(xiàn)

使用技巧:
設(shè)置參數(shù)默認(rèn)值 關(guān)鍵字傳參
序列傳參 字典傳參 接收序列 接收字典
返回值包含多個(gè)數(shù)據(jù)

# 函數(shù)的使用技巧-1
# 1. 為參數(shù)設(shè)置默認(rèn)值,只需要在形參后面增加 "= 具體值" 即可
def calc_exchange_rate(amt, source="CNY", target="USD"):
    print(target)
    if source == "CNY" and target == "USD":
        # 6.7516 : 1
        result = amt / 6.7516
        # print(result)
        print("匯率計(jì)算成功")
        return result
    elif source == "CNY" and target == "EUR":
        result = amt / 7.7512
        return result


print(calc_exchange_rate(100))


# 2. 以形參形式傳參(關(guān)鍵字傳參)
def health_check(name, age, height, weight, hr, hbp, lbp, glu):
    print("您的健康狀況良好")


health_check(name="張三", height=178, age=32, weight=85.5, hr=70, hbp=120, lbp=80, glu=4.3)

# 函數(shù)的使用技巧-2
# 1. 序列傳參
def calc(a, b, c):
    return (a + b) * c


l = [1, 5, 10]
print(calc(*l))


# 2. 字典傳參
def health_check(name, age, height, weight, hr, hbp, lbp, glu):
    print(name)
    print(height)
    print(hr)
    print("您的健康狀況良好")


param = {"name": "張三", "height": 178, "age": 32, "weight": 85.6, "hr": 70, "hbp": 120, "lbp": 80, "glu": 4.3}
health_check(**param)

# 3. 返回值包含多個(gè)數(shù)據(jù)
def get_detail_info():
    dict1 = {
        "employee" : [
            {"name":"張三", "salary":1800},
            {"name":"李四", "salary":2000}
        ],
        "device" : [
            {"id" : "8837120" , "title" : "XX筆記本"},
            {"id" : "3839011" , "title" : "XX臺(tái)式機(jī)"}
        ],
        "asset" :[{},{}],
        "project" :[{},{}]
    }
    return dict1
print(get_detail_info())
d = get_detail_info()
sal = d.get("employee")[0].get("salary")
print(sal)

# 補(bǔ)充
def cheeseshop(kind, *arguments, **keywords):
    print("-- Do you have any", kind, "?")
    print("-- I'm sorry, we're all out of", kind)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    for kw in keywords:
        print(kw, ":", keywords[kw])
cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch")
Result:
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch

2 模塊與包

導(dǎo)入

import os
當(dāng)前包 -> 內(nèi)置函數(shù) -> 環(huán)境變量

屬性

dir 列出對(duì)象的所有屬性與方法
help 查看類; 方法的幫助信息
__name__ 模塊的名稱
__file__ 文件路徑

引用

import package 只是import了init.py
from package.xx.xx import xx 引入需要的屬性和方法
from package.xx.xx import xx as rename 指定別名
from package.xx.xx import * 引入所有屬性和方法

3 標(biāo)準(zhǔn)模塊與第三方模塊

標(biāo)準(zhǔn)模塊

os:
environ system(command) sep pathsep linesep urandom(n) argv getcwd modules path platform mkdir/rmdir os.path
DateTime:
timedelta date datetime.strftime datetime.strptime time datetime.now day days

第三方模塊

Django
Flask
mysqlclient

4 自定義包的實(shí)現(xiàn)

https://chriswarrick.com/blog/2018/09/04/python-virtual-environments/

virtualenv:

pip install virtualenv; cd /home/envs; virtualenv name; activate/deactivate

pipenv

5 常用高階函數(shù)

lambda
filter, map, reduce:
filter(lambda n: n% 2 !=0, [1,2,3,4,5])
my_list = [12,3,45,6]
print(sorted(my_list, key=lambda x: x>0))
stus = [{},{}]
suts.sort(key=lambda x: x['age'])
map(function, sequence, ...)
reduce(lambda m, n: m + n, [1,2,3,4,5])

6 文件讀寫模式

'r' 'w' 'x' 'a' 'b' 't' '+'

with open("file.txt", 'r') as f:
  do(f)

調(diào)整文件指針位置:file.seek(0)
read() 讀指定長(zhǎng)度內(nèi)容
readline() 讀單行
簡(jiǎn)單寫法:

>>> for line in f:
...     print(line, end='')
...
This is the first line of the file.
Second line of the file

readlines() 讀完放在一個(gè)list里
write() write expects a single string.
writelines() writelines expects an iterable of strings
https://stackoverflow.com/questions/12377473/python-write-versus-writelines-and-concatenated-strings
f.tell() 顯示位置
json can handle lists and dictionaries, pickle can handle complex python objects

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1. 函數(shù) 1.1 介紹 課時(shí)介紹(1) 函數(shù)介紹。(2) 函數(shù)參數(shù)與返回值。(3) 函數(shù)應(yīng)用。 目標(biāo)(1) 掌握...
    nimw閱讀 672評(píng)論 0 0
  • 寫在前面的話 代碼中的# > 表示的是輸出結(jié)果 輸入 使用input()函數(shù) 用法 注意input函數(shù)輸出的均是字...
    FlyingLittlePG閱讀 3,219評(píng)論 0 9
  • 高階函數(shù):將函數(shù)作為參數(shù) sortted()它還可以接收一個(gè)key函數(shù)來(lái)實(shí)現(xiàn)自定義的排序,reversec參數(shù)可反...
    royal_47a2閱讀 835評(píng)論 0 0
  • http://python.jobbole.com/85231/ 關(guān)于專業(yè)技能寫完項(xiàng)目接著寫寫一名3年工作經(jīng)驗(yàn)的J...
    燕京博士閱讀 7,804評(píng)論 1 118
  • 姓名:魏正君《六項(xiàng)精進(jìn)》第270期感謝2組公司:綿陽(yáng)大北農(nóng)農(nóng)牧科技有限公司【日精進(jìn)打卡第423天】【知~學(xué)習(xí)】背誦...
    莫心莫肺閱讀 89評(píng)論 0 0

友情鏈接更多精彩內(nèi)容