#same output: hello python!
print('hello python!')
print("hello python!")
print('''hello python!''')
print("""hello python!""")
#print ASCII
print(chr(65)) #A
print(ascii(65)) #65
print(ord('A')) #65
print(ord('你')) #20013'
print(ord('好')) #25105'
#print multiple value
print('hello','python!')
print('hello', 'python!',sep=',',end='???')
print('你好') #默认end为\n,前一语句改变了这个值,所以输出在一行
#print to file
f = open('test.txt', 'w')
print('hello python!', file=f)
f.close()
#print to stdout
import sys
print('hello python!', file=sys.stdout)
#input
print('please input your name:')
name = input()
print('hello', name) #python3中input返回的是字符串类型,不需要在加引号了
'''
养成良好的编程习惯:
1. 缩进
2. 变量命名
3. 函数命名
4. 代码注释
'''
#中文文档声明注释
'''
一定是写在文件第一行
语法格式如下:
# -*- coding: 编码 -*-
或者
# coding=编码
例:
# -*- coding: utf-8 -*-
在Python中提供一种特殊的中文编码声明注释,
该注释的出现主要是为了解决Python 2.x中不支持直接写中文的问题。
虽然在Python 3.x中,该问题已经不存在了。
但是为了规范页面的编码,同时方便其他程序员及时了解文件所用的编码,建议在文件开始加上中文编码声明注释。
'''
'''
python保留字
'''
import keyword
print(keyword.kwlist)
数值类型
#number
num1=78
num2=0b1010101 #2进制数
num3=0x4E #16进制
num4=0o66 #8进制
print(num1,num2,num3,num4) #输出值为10进制的数
num6=12+5j #复数
print(num6.real,num6.imag) #输出值为12.556 0.0) #输出值为12.556
num7=0.2
num8=0.3
print(num7+num8) #输出值为0.5
print(round(num7,1)) #输出值为0.2
print(round(num7+num8,2)) #输出值为0.5
print(0.2+0.3) #输出值为0.5
print(format(0.2+0.3,'.4f')) #输出值为0.5000
字符串类型
print('hello123\tPython.') #\t 一个制表符是8位,前面字符占n*8个位置,不满的空格补
print('hello123456\tPython.') #\t
print('hello\tPython.')
print('hello \vPython.') #\v 垂直制表符,与\t相同,只是方向相反,向下移动
'''
--------------
hello123 Python.
hello123456 Python.
hello Python.
hello
Python.
--------------
'''
#切片
var1= 'hello world'
print(var1[0]) #h
print(var1[0:5]) #hello 前闭后开,从0开始到5(不包括5)
print(var1[-1:]) #d 负数表示从后往前数,-1表示倒数第一个字符
print(var1[-1:-3])#空
print('Hello' in var1) #False 判断字符串是否包含子串 判断区分大小写
布尔值
True 整数1, False 整数0
布尔值为False的情况
- False, None
- 数值中的0, 0.0,虚数0
- 空序列,包括空字符串,空元组,空列表,空集合
- 自定义对象的实例,该对象的_bool_()返回False或者_len_()返回0
数组 list
元组 tuple
不可变
字典 dic
集合 set
add 重复值会自动弃掉
remove(key) discard(key):key不存在时不会报错
生成式
'''
生成20个100以内的随机整数,将其中前10个升序排列,后10个降序排列,并输出结果
'''
import random
lst = [random.randint(1, 100) for _ in range(20)]
print(lst)
#前面十个升序 后面十个降序
lst = sorted(lst[:10]) + sorted(lst[10:], reverse=True)
print(lst)
lst =[]
for i in range(20):
lst.append(random.randint(1, 100))
print(lst)
#前面十个升序 后面十个降序
lst = sorted(lst[:10]) + sorted(lst[10:], reverse=True)
print(lst)
#列表生成式 双层循环
lst = [i+j for i in ['孙','李','王','张'] for j in ['伯','仲','叔','季']]
print(lst)
#列表生成式 三层循环 循环i*j*k次
lst=[i+j+k for i in 'ABC' for j in 'XYZ' for k in '123']
print(lst)
print(len(lst))
第一种生成方法非常简洁,多层循环可以实现穷举
杨辉三角
yield生成器
def yanghui_triangle():
lst =[1]
while True:
yield lst
lst = [lst[i-1]+lst[i] for i in range(1, len(lst))]
lst.insert(0,1)
lst.append(1)
if __name__ == '__main__':
yanghui_triangle = yanghui_triangle()
for i in range(10):
print(next(yanghui_triangle))
输出格式
匹配输出的几种方式:
score=input("请输入你的成绩")
switcher={
"A":90,
"B":80,
"C":70,
"D":60,
"E":50,
"F":40,
}
print(switcher.get(score, "输入错误"))
match score:
case "A":
print(90)
case "B":
print(80)
case "C":
print(70)
case "D":
print(60)
case "E":
print(50)
case "F":
print(40)
case _:
print("输入错误")
嵌套循环练习
#打印直角正三角形
for i in range(1,6):
for j in range(1,i+1):
print("*",end="")
print()
#打印直角倒三角形
for i in range(1,6):
for j in range(1,6-i):
print("*",end="")
print()
#打印正三角形
for i in range(1,6):
print(" "*(5-i)+"*"*(2*i-1))
#for j in range(i,I+1):
#打印倒三角形
for i in range(5,0,-1):
print(" "*(5-i)+"*"*(2*i-1))
#打印实心菱形
for i in range(1,6):
print(" "*(5-i)+"*"*(2*i-1))
for i in range(4,0,-1):
print(" "*(5-i)+"*"*(2*i-1))
#打印空心三角形
for i in range(1,6):
if (i>1):
print(" "*(5-i)+"*" +" "*(2*i-3) +"*")
else:
print(" "*(5-i)+"*")
#打印空心菱形
for i in range(1,6):
if (i>1):
print(" "*(5-i)+"*" +" "*(2*i-3) +"*")
else:
print(" "*(5-i)+"*")
for i in range(4,0,-1):
if (i!=1):
print(" "*(5-i)+"*" +" "*(2*i-3) +"*")
else:
print(" "*(5-i)+"*")
'''
*
**
***
****
*****
****
***
**
*
*
***
*****
*******
*********
*********
*******
*****
***
*
*
***
*****
*******
*********
*******
*****
***
*
*
* *
* *
* *
* *
*
* *
* *
* *
* *
* *
* *
* *
*
'''
索引
正向索引 0....N-1
反向索引-N......-1
序列切片 list[start:end:step] 返回新的序列 step为负数的话是逆序
列表名=list(序列) #定义列表
格式化字符串
占位符 %d %s %f
f-string python3.6引入
str.format()
name='Lily'
age=18
score=98.5
'''
Name:Lily,Age:18,Score:98.500000
Name:Lily,Age:18,Score:98.5
Name:Lily,Age:18,Score:98.5
Name:Lily,Age:18,Score:98.5
'''
print('Name:%s,Age:%d,Score:%f'%(name,age,score)) #占位符
print('Name:%s,Age:%d,Score:%.1f'%(name,age,score)) #格式化占位符
print(f'Name:{name},Age:{age},Score:{score}') #f-string
print('Name:{0},Age:{1},Score:{2}'.format(name,age,score)) #str.format
str1='Hello python!'
#居中显示 ^
print("{0:'^20}".format(str1))
print(str1.center(20,'\''))
print('{0:,.2f}'.format(8983456.123478))
print('十进制:{0:d}, 二进制:{0:b}, 八进制:{0:o},十六进制:{0:x},十六进制:{0:X}'.format(456))
'''
输出:
'''Hello python!''''
'''Hello python!''''
8,983,456.12
十进制:456, 二进制:111001000, 八进制:710,十六进制:1c8,十六进制:1C8
'''
字符串编码/解码
str1="北京欢迎你"
scode1=str1.encode()
print(scode1) #默认编码为utf-8:英文字母占1个字节,汉字占3个字节
scode1=str1.encode(encoding='gbk')
print(scode1) #编码为gbk:英文字母占1个字节,汉字占2个字节
其它判断函数
print('123'.isdigit()) # True 只能判断阿拉伯数字
print('一百二'.isnumeric()) # True 还可以识别中文数字
print('Ⅷ'.isnumeric()) # True 还可以识别罗马数字
print('壹佰贰拾伍'.isnumeric()) # True 还可以识别中文数字大写
中文大写数字转换来源于:
函数参数
def fun(*arg):
print(arg)
def fun2(**arg):
for key, value in arg.items():
print(key, value) # 输出字典的键值对
fun(1, 2, 3)
lst=[1, 2, 3]
fun(*lst) # 解包列表
fun2(Name="张三", age=24, score=39)
dic={"Name": "李四", "age": 23, "score": 89}
fun2(**dic) # 解包字典
匿名函数lambda
fun=lambda a,b,c:a+b+c
print(fun(1,2,3))
list_dic=[{'name':'zhangsan','age':20},{'name':'lisi','age':21},{'name':'wangwu','age':22}]
list_dic_sort=sorted(list_dic,key=lambda x:x['age'],reverse=True)
print(list_dic_sort)
list_dic.sort(key=lambda x:x['age'],reverse=True)
print(list_dic)
迭代器操作函数
lst=[23,89,908,767,38]
list_sorted=sorted(lst,reverse=True)
print(list_sorted)
list_sorted.reverse()
list_sorted=reversed(list_sorted)
print(list_sorted) #list_reverseiterator object 迭代器对象
#print(list(list_sorted)) #迭代器对象使用一次后,内容就为空了;比如这里打印完后,下面的zip_list就为空了
zip_list=zip(lst,list(list_sorted)) #将两个列表中的元素配对,并返回一个元组列表
print(list(list_sorted)) #输出[],因为前面已经用过了
print(zip_list)
print(list(zip_list)) #[(23, 908), (89, 767), (908, 89), (767, 38), (38, 23)]
zip_list=zip(lst,[i for i in range(6)]) # 按最少的组合,多余的元素被舍弃
print(list(zip_list)) #[(23, 0), (89, 1), (908, 2), (767, 3), (38, 4)]
print(tuple(enumerate(lst)))#((0, 23), (1, 89), (2, 908), (3, 767), (4, 38))
'''
reduce 函数会对一个序列(如列表、元组等)的元素进行累积计算,返回一个单一的结果值
'''
from functools import reduce
numbers = [1, 2, 3, 4, 5]
sum = reduce((lambda x, y: x + y), numbers)
print(sum) # 输出: 15
闭包函数
1.函数嵌套定义
2.外部函数返回内部函数的定义
3.内部函数使用了外部函数的临时参数
闭包函数最常见的情景:实现数据私有化
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
# 创建一个计数器
my_counter = make_counter()
print(my_counter()) # 输出: 1
print(my_counter()) # 输出: 2
# 外部无法直接访问 count 变量
模块导入
-
导入整个模块:
import module_name
使用这种方式后,你需要通过模块名来访问其属性,例如
module_name.function()
。 -
导入整个模块,并为其设置别名:
import module_name as alias
设置别名后,可以使用简短的别名来访问模块的属性,例如
alias.function()
。 -
从模块中导入特定的函数或类:
from module_name import object_name
这样可以直接使用导入的对象而不需要模块名前缀,例如
object_name()
。 -
从模块中导入多个特定的函数或类:
from module_name import first_object, second_object
你可以在一条语句中导入多个对象。
-
从模块中导入所有对象(不推荐,因为这会污染命名空间):
from module_name import *
-
从模块中导入对象,并为其设置别名:
from module_name import object_name as alias
导入时设置别名,之后可以通过别名访问该对象,例如
alias()
。 -
从包中导入模块: 如果模块是包的一部分,你需要指定完整的路径:
from package_name.subpackage_name import module_name
-
使用相对导入(只能在包内部使用): 相对导入用于在包内部导入其他模块或包:
from . import module_name from .module_name import object_name from ..subpackage_name import module_name
-
延迟导入: 延迟导入是指在函数或方法内部进行导入,而不是在文件顶部。这可以用于控制模块的加载时机,例如:
def function(): from module_name import object_name object_name()
from module_name import *
可以通过__all__变量配置 * 可以导入哪些
a.py
__all__=['fun1']
def fun1():
print('fun1')
def fun2():
print('fun2')
b.py
from a import *
fun1()
fun2()
报错:NameError: name 'fun2' is not defined. Did you mean: 'fun1'?
没用变量的话,全部都可以引入;如果用了,只能引入限定的
配置包搜索路径
1.修改环境变量
通过修改PYTHONPATH
环境变量,可以添加额外的搜索路径。这个环境变量可以包含多个路径,用冒号(:
)分隔(在Unix-like系统中)或分号(;
)分隔(在Windows系统中)。
2.使用sys.path
Python的sys
模块包含一个名为path
的列表,它定义了解释器搜索模块的路径。你可以在代码中动态地修改这个列表:
import sys sys.path.append('/path/to/your/directory')
3.使用.pth文件
在site-package添加一个文件,文件以pth结尾。
window: python安装路径\Lib\site-packages
ubuntu: /usr/local/lib/python3.11/dist-packages
Package(包)Module(模块)
包是一个文件夹,必须包含__init__.py文件
二进制文件写入
struct模块
pickle模块 (更简洁一些)
import pickle
try:
with open("data.pkl", "wb") as f:
pickle.dump({"name": "张三", "age": 30}, f)
pickle.dump(100, f)
pickle.dump('EOF', f)
print("write file success")
except:
print("write file error")
print("=========================")
#load 不能判断文件是否结束,所以需要try except
#可以选择在写入文件的时候,开头写入data的数量,然后读取的时候读取数量,读取完数量个data就结束
#或者用'EOF'作为结束标志,写入的时候写入'EOF',读取的时候判断是否为'EOF',为'EOF'时结束读取
try:
with open("data.pkl", "rb") as f:
while True:
data = pickle.load(f)
print(data)
if data == 'EOF':
break
print("read file success")
except:
print("read file error")
bmp文件的读写
读取并上下翻转bmp文件
import struct
with open('05.bmp','rb') as img1:
fileHeader = img1.read(54) #read the first 54 bytes of the file: it's header info for bmp image
print(fileHeader)
pixel_buffer = img1.read() #read the rest of the file: it's the pixel buffer
img1.seek(18)
size = img1.read(8)
width, height = struct.unpack('ii', size)
print('image width:{0: ^10},height:{1: ^10}'.format(width, height))
#将图片上下翻转
if(len(pixel_buffer) == width*height*3): #check if the pixel buffer size is correct
print('start to convert bmp file')
pixel_list = list(pixel_buffer)
for i in range(0, height//2):
pixel_list[i*width*3:(i+1)*width*3], pixel_list[(height-i-1)*width*3:(height-i)*width*3] = \
pixel_list[(height-i-1)*width*3:(height-i)*width*3], pixel_list[i*width*3:(i+1)*width*3]
pixel_buffer_new = bytes(pixel_list)
else:
print('pixel buffer size is incorrect')
with open('5_new.bmp','wb') as img2:
img2.write(fileHeader)
img2.write(pixel_buffer_new)
另一方法,需要按照pillow
from PIL import Image
# 打开BMP文件
img = Image.open('path_to_your_bmp_file.bmp')
# 水平翻转图像
flipped_img = img.transpose(Image.FLIP_LEFT_RIGHT)
# 垂直翻转图像,你也可以使用 Image.FLIP_TOP_BOTTOM
# flipped_img = img.transpose(Image.FLIP_TOP_BOTTOM)
# 显示图像
flipped_img.show()
# 保存翻转后的图像
flipped_img.save('path_to_save_flipped_bmp_file.bmp')
CSV文件读写
导入csv模块
装饰器
利用了闭包函数,包裹目标函数
装饰器可以接受参数
装饰器可以用在类上
# 定义一个装饰器
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
# 使用装饰器
@my_decorator
def say_hello():
print("Hello!")
say_hello()
def pre(name):
def decorator_function(func):
def wrapper(*args, **kwargs):
print(name + " said:")
result = func(*args, **kwargs)
return result
return wrapper
return decorator_function
@pre(name='Tom')
def greet(name):
print(f"Hello {name}!")
greet("Alice")