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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1. 函数 1.1 介绍 课时介绍(1) 函数介绍。(2) 函数参数与返回值。(3) 函数应用。 目标(1) 掌握...
    nimw阅读 665评论 0 0
  • 写在前面的话 代码中的# > 表示的是输出结果 输入 使用input()函数 用法 注意input函数输出的均是字...
    FlyingLittlePG阅读 3,199评论 0 9
  • 高阶函数:将函数作为参数 sortted()它还可以接收一个key函数来实现自定义的排序,reversec参数可反...
    royal_47a2阅读 824评论 0 0
  • http://python.jobbole.com/85231/ 关于专业技能写完项目接着写写一名3年工作经验的J...
    燕京博士阅读 7,773评论 1 118
  • 姓名:魏正君《六项精进》第270期感谢2组公司:绵阳大北农农牧科技有限公司【日精进打卡第423天】【知~学习】背诵...
    莫心莫肺阅读 89评论 0 0

友情链接更多精彩内容