Python进阶——函数

  • 函数
  • 一、格式
  • 二、参数
  • 形参、实参
  • 默认参数
  • 关键参数(指定参数)
  • 非固定参数
  • 局部变量&全局变量
  • 函数传字典、列表的特殊现象
  • 三、常用内置函数
  • 模块
  • 模块导入
  • 自定义模块
  • 第三方开源模块
  • 常用模块
  • os模块
  • sys模块
  • time模块
  • datetime模块
  • random模块


函数

一、格式

def sayhi(): #函数名
	print('hello,world')
sayhi() #调用
def sayhi(x,y): #函数名
	print(f'{x}hello,{y}world')
sayhi(x,y) #调用

二、参数

形参、实参

python chunks函数 python函数sample_时间戳

默认参数

默认参数放在形参的最后,调用函数未指定时使用默认参数,指定时使用指定的值

def hhh(x, y, z, w = 5)
	print(x+y+z+w)
hhh(1,2,3)
hhh(1,2,3,4)

关键参数(指定参数)

调用函数时按位置顺序传入的参数叫位置参数
如果调用函数传参时指定的参数名,则叫指定参数、即关键参数

指定参数必须放在位置参数后面

def hhh(x, y, z, w)
	print(x+y+z+w)
hhh(1,2,w=3,z=5)	# 指定参数

非固定参数

当不知道用户会传进来多少参数时,定义非固定参数解决用户传参过多报错的问题

用*args保存多输的实参,以元组形式保存

def stu_data(name, age, gender, *args): # 多输的参数会在args中以元组形式保存
    print(name, age, gender, *args, args)
    
stu_data('小明', 12, 'M', '河南', '中国')

>>>小明 12 M 河南 中国 ('河南', '中国')

用**kwargs保存多输的实参,以字典形式保存

def stu_data(name, age, gender, **kwargs): # 多输的参数会在**kwargs中以字典形式保存
    print(name, age, gender, kwargs,)

stu_data('小明', 12, 'M', province='河南', 国籍='中国')

>>>小明 12 M {'province': '河南', '国籍': '中国'}

局部变量&全局变量

1、函数外声明为全局变量,函数内声明为局部变量
2、函数内查找顺序先局部后全局,没有局部时默认使用全局。
3、函数内更改局部变量不能改变全局变量
4、函数内可以使用 global 变量名 来声明全局变量

函数传字典、列表的特殊现象

可在函数中改变外部传入的字典与列表

三、常用内置函数

python chunks函数 python函数sample_字符串_02


以上均为Python内置函数,具体见官网 简单介绍几个常用的:

  1. abs() 求绝对值
  2. all() 对列表中每个元素进行bool()判断,全为真才返回true
  3. any() 对列表中每个元素进行bool()判断,任一为true,返回true
  4. ascii #Return an ASCII-only representation of an object,ascii(“中国”) 返回”‘\u4e2d\u56fd’”
  5. bin #返回整数的2进制格式
  6. bool() 判断⼀个数据结构是True or False, bool({}) 返回就是False, 因为是空dict
  7. bytearray # 把byte变成 bytearray, 可修改的数组
  8. bytes # bytes(“中国”,”gbk”)
  9. callable # 判断⼀个对象是否可调⽤
  10. chr()返回⼀个数字对应的ascii字符 , 比如chr(90)返回ascii⾥的’Z’
  11. classmethod #⾯向对象时⽤,现在忽略
  12. compile #py解释器⾃⼰⽤的东⻄,忽略
  13. complex #求复数,⼀般⼈⽤不到
  14. copyright #没⽤
  15. credits #没⽤
  16. delattr #⾯向对象时⽤,现在忽略
  17. dict()生成⼀个空字典
  18. dir() 返回当前程序所有的变量名
  19. divmod #返回除法的商和余数 ,⽐如divmod(4,2),结果(2, 0)
  20. enumerate返回列表的索引和元素,比如 d = [“alex”,”jack”],enumerate(d)后,得到(0, ‘alex’)
    (1, ‘jack’)
  21. eval #可以把字符串形式的list,dict,set,tuple,再转换成其原有的数据类型。
  22. exec #把字符串格式的代码,进⾏解义并执⾏,⽐如exec(“print(‘hellworld’)”),会解义⾥⾯的字符
    串并执⾏
  23. exit 退出程序
  24. filter(函数名,列表) #对list、dict、set、tuple等可迭代对象进行过滤,将列表中每项元素带入函数中,若为真保留
  25. float()转成浮点
  26. format #没⽤
  27. frozenset #把⼀个集合变成不可修改的
  28. getattr #⾯向对象时⽤,现在忽略
  29. globals #打印全局作⽤域⾥的值
  30. hasattr #⾯向对象时⽤,现在忽略
  31. hash #hash函数
  32. help()
  33. hex #返回⼀个10进制的16进制表示形式,hex(10) 返回’0xa’
  34. id()查看对象内存地址
  35. input()
  36. int()
  37. isinstance #判断⼀个数据结构的类型,⽐如判断a是不是fronzenset, isinstance(a,frozenset) 返
    回 True or False
  38. issubclass #⾯向对象时⽤,现在忽略
  39. iter #把⼀个数据结构变成迭代器,讲了迭代器就明⽩了
  40. len()返回长度
  41. list()创建一个列表
  42. locals()以键值对形式打印当前程序中所有变量名和变量值
  43. map(函数名不加括号,可循环列表等)
l = list(range(10))
def cacl(x):
    return x**2
m = map(cacl, l)  # 函数名后不加括号,只丢给cacl但并不执行
for i in m:     # 遍历时开始执行
    print(i, end=',')
  1. max() 求最大值
  2. memoryview # ⼀般⼈不⽤,忽略
  3. min()求最⼩值
  4. next # ⽣成器会⽤到,现在忽略
  5. object #⾯向对象时⽤,现在忽略
  6. oct # 返回10进制数的8进制表示
  7. open
  8. ord()返回字符对应的ascii码值
  9. print
  10. property #⾯向对象时⽤,现在忽略
  11. quit
  12. range
  13. repr #没什么⽤
  14. reversed # 可以把⼀个列表反转
  15. round()可以把小数4舍5⼊成整数 ,round(10.15,1) 得10.2
  16. set
  17. setattr #⾯向对象时⽤,现在忽略
  18. slice # 没⽤
  19. sorted
  20. staticmethod #⾯向对象时⽤,现在忽略
  21. str()变为字符串
  22. sum() 求和,a=[1, 4, 9, 1849, 2025, 25, 36],sum(a) 得3949
  23. super #⾯向对象时⽤,现在忽略
  24. tuple
  25. type
  26. vars #返回⼀个对象的属性,⾯向对象时就明⽩了
  27. zip()配对
a = [1,2,3]
b = ['a','b','c','d']
for i in zip(a,b):
    print(i)

>>>(1, 'a')
(2, 'b')
(3, 'c')

模块

模块导入

import module_a #导⼊
from module import xx # 导⼊某个模块下的某个⽅法 or ⼦模块
from module.xx.xx import xx as rename #导⼊后⼀个⽅法后重命令
from module.xx.xx import * #导⼊⼀个模块下的所有⽅法,不建议使⽤

自定义模块

调用自定义模块时一定要在同级目录下,否则需要用sys模块导入自定义模块路径
调用模块会自动运行模块中的程序

"""所需模块名为first_module,路径为D:\\programming\\python\\learnPython\\路飞学城8天集训营\\test_module\\test_module.py"""
"""当前文件路径为D:\\programming\\python\\learnPython\\路飞学城8天集训营\\import_module.py"""
import sys
print(sys.path)  # 显示查找模块的路径,是一个列表
# 若所需模块不在文件同级目录下,则应把模块所在路径添加到sys.path中
#sys.path.append('D:\\programming\\python\\learnPython\\路飞学城8天集训营\\test_module')

# 因为不同电脑的路径不同,为了可移植,改为动态路径
import os
print(__file__) #打印当前脚本文件路径
path = os.path.dirname(__file__) # 当前脚本的根目录路径
print(path)
sys.path.append(path+'/test_module')

import first_module
first_module.sayhi()

第三方开源模块

官网豆瓣源(https://pypi.douban.com/simple/)
清华源(https://pypi.tuna.tsinghua.edu.cn/simple)
下载方法:

  1. pip install + 包名
  2. Pycharm中设置-项目-python解释器-加号(管理仓库按键中可以添加源)
  3. pip install -i https://pypi.douban.com/simple/ + 包名 --trusted-host pypi.douban.com
  4. 升级pippython -m pip install --upgrade pip -i https://pypi.douban.com/simple
  5. 升级pippython -m pip install -i https://pypi.douban.com/simple/ --upgrade pip

包就是在目录的基础上加了一个__init__.py文件,每次调用包内文件,都会先执行__init__.py文件来初始化

常用模块

os模块

帮助实现程序与操作系统进行交互

  • 得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd()
  • 返回指定目录下的所有文件和目录名:os.listdir()
  • 函数用来删除⼀个文件:os.remove()
  • 删除多个目录:os.removedirs(r“c:\python”)
  • 检验给出的路径是否是⼀个文件:os.path.isfile()
  • 检验给出的路径是否是⼀个目录:os.path.isdir()
  • 判断是否是绝对路径:os.path.isabs()
  • 检验路径是否存在:os.path.exists()
  • 返回⼀个路径的目录名和文件名:os.path.split() e.g
    os.path.split(’/home/swaroop/byte/code/poem.txt’) 结果:
    (’/home/swaroop/byte/code’, ‘poem.txt’)
  • 分离扩展名:os.path.splitext() e.g os.path.splitext(’/usr/local/test.py’)
    结果:(’/usr/local/test’, ‘.py’)
  • 获取路径名:os.path.dirname()
  • 获得绝对路径: os.path.abspath()
  • 获取文件名:os.path.basename()
  • 运行shell命令: os.system()
  • 读取操作系统环境变量HOME的值:os.getenv(“HOME”)
  • 返回操作系统所有的环境变量: os.environ
  • 设置系统环境变量,仅程序运行时有效:os.environ.setdefault(‘HOME’,’/home/alex’)
    给出当前平台使用的行终止符:os.linesep Windows使用’\r\n’,Linux and MAC使用’\n’
    指示你正在使用的平台:os.name 对于Windows,它是’nt’,⽽对于Linux/Unix用户,它
    是’posix’
  • 重命名:os.rename(old, new)
  • 创建多级目录:os.makedirs(r“c:\python\test”)
  • 创建单个目录:os.mkdir(“test”)
  • 获取文件属性:os.stat(file)
  • 修改文件权限与时间戳:os.chmod(file)
  • 获取文件大小:os.path.getsize(filename)
  • 结合目录名与文件名:os.path.join(dir,filename)
  • 改变工作目录到dirname: os.chdir(dirname)
  • 获取当前终端的大小: os.get_terminal_size()
  • 杀死进程: os.kill(10884,signal.SIGKILL)

sys模块

  • sys.path() 获取环境变量
  • sys.argv()

time模块

python中表示时间的方式

  • 时间戳(timestamp), 表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。例子:1554864776.161901
  • 格式化的时间字符串,比如“2020-10-03 17:54”
  • 元组(struct_time)共九个元素。由于Python的time模块实现主要调⽤C库,所以各个平台可能有所不同,mac上:time.struct_time(tm_year=2020, tm_mon=4, tm_mday=10, tm_hour=2,tm_min=53, tm_sec=15, tm_wday=2, tm_yday=100, tm_isdst=0)

    UTC时间
    即格林尼治标准时间,中国在东八区,即UTC+8
    常用方法
  • time.localtime([secs]) 将⼀个时间戳转换为当前时区的struct_time。若secs参数未提供,则以当前时间为准。
  • time.gmtime([secs]) 和localtime()方法类似,gmtime()方法是将⼀个时间戳转换为UTC时区(0时区)的struct_time。
  • time.time() 返回当前时间的时间戳。
  • time.mktime(t) 将⼀个struct_time转化为时间戳。
  • time.sleep(secs) 线程推迟指定的时间运行,单位为秒。
  • time.strftime(format[, t]) 把⼀个代表时间的元组或者struct_time(如由time.localtime()和time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()
  • time.strptime(string[, format]) 把⼀个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作
import time
print(time.strftime("%Y-%m-%d %X",time.localtime()))
>>>2021-10-03 14:46:53

%y 两位年份 %m 月份 %H 24小时制小时数 %M 分钟数 %a 星期简写 %b 月份简写
%Y 四位年份 %d 日期 %I 12小时制小时数 %S …秒… %A 星期全拼 %B 月份全拼
%p AM或PM %z 当前时区
%j 今年的第几天
%w 这周的第几天,周末为0
%x 本地特定日期表示
%X 本地特定时间表示
%U 今年的第几个星期,周末为星期开始
%W 今年的第几个星期,周一为星期开始

datetime模块

import datetime
d = datetime.datetime.now()
print(datetime.datetime.now()) # 打印当前时间
>>>2021-10-03 16:21:46.192961
print(datetime.datetime.now() + datetime.timedelta(4)) # 当前时间加4天
>>>2021-10-07 16:21:46.192961
print(datetime.datetime.now() + datetime.timedelta(hours=3)) # 当前时间加3小时
>>>2021-10-03 19:21:46.192961
print(d.replace(year=2025, month=2, day=28)) # 替换时间
>>>2025-02-28 16:21:46.192961

random模块

python chunks函数 python函数sample_pycharm_03