Python基础语法 - 2 Python函数与模块

1 函数定义传参
2 模块和包
3 标准包和第三方包和虚拟环境
4 高阶函数 map filter reduce
5 文件读写和json和pickle

1 函数的定义和实现

使用技巧:
设置参数默认值 关键字传参
序列传参 字典传参 接收序列 接收字典
返回值包含多个数据

# 函数的使用技巧-1
# 1. 为参数设置默认值,只需要在形参后面增加 "= 具体值" 即可
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("汇率计算成功")
        return result
    elif source == "CNY" and target == "EUR":
        result = amt / 7.7512
        return result


print(calc_exchange_rate(100))


# 2. 以形参形式传参(关键字传参)
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)

# 函数的使用技巧-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. 返回值包含多个数据
def get_detail_info():
    dict1 = {
        "employee" : [
            {"name":"张三", "salary":1800},
            {"name":"李四", "salary":2000}
        ],
        "device" : [
            {"id" : "8837120" , "title" : "XX笔记本"},
            {"id" : "3839011" , "title" : "XX台式机"}
        ],
        "asset" :[{},{}],
        "project" :[{},{}]
    }
    return dict1
print(get_detail_info())
d = get_detail_info()
sal = d.get("employee")[0].get("salary")
print(sal)

# 补充
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 模块与包

导入

import os
当前包 -> 内置函数 -> 环境变量

属性

dir 列出对象的所有属性与方法
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 标准模块与第三方模块

标准模块

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 自定义包的实现

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

virtualenv:

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

pipenv

5 常用高阶函数

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)

调整文件指针位置:file.seek(0)
read() 读指定长度内容
readline() 读单行
简单写法:

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

readlines() 读完放在一个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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值