python3基础语法
注释&模块
# 这是一个注释,如:导入模块
import math
"""
这是一个块注释
当模块被直接运行时,__name__等于"__main__"
当模块被导入时,__name__等于模块名
"""
if __name__ == "__main__":
print("模块被直接运行")
else:
print("模块被导入")
# ```
# 这也是一个多行注释
# ```
# 当模块被直接运行时,__name__等于"__main__"
# 当模块被导入时,__name__等于模块名
#
数据结构
# 基础类型
a = 100 # 整数
b = 100.0 # 浮点数
c = 100.0j # 复数
d = 'hello' # 字符串
e = True # 布尔值
f = None # 空值
# 内置数据结构:list(a), tuple(a), set(a), dict(a)
#### 列表
fruits = ['apple', 'banana', 'cherry'] # 创建列表
print(fruits[0]) # apple 访问元素
fruits[1] = 'orange' # 修改元素
fruits.append('grape') # 添加元素
del fruits[2] # 删除元素
print(fruits[1:3]) # ['banana', 'cherry'] # 列表切片
#### 元组
colors = ('red', 'green', 'blue') # 创建元组(不可变)
print(colors[1]) # green 访问元素
a, b, c = colors # 元组解包
#### 字典
person = {'name': 'John', 'age': 30} # 创建字典
print(person['name']) # John 访问值
person['city'] = 'New York' # 添加/修改键值对
del person['age'] # 删除键值对
for key, value in person.items(): # 遍历字典
print(f"{key}: {value}")
#### 集合
unique_numbers = {1, 2, 3, 3, 4} # 创建集合# {1, 2, 3, 4}
unique_numbers.add(5) # 添加元素
unique_numbers.remove(3) # 删除元素
a = {1, 2, 3} # 集合运算
b = {3, 4, 5}
print(a | b) # 并集 {1, 2, 3, 4, 5}
print(a & b) # 交集 {3}
# 强制类型转换
y = int('100') # 整数化
z = float('3.14') # 浮点数化
aa = complex(a) # 复数化
ii = type(a) # 类型
gg = bool(100) # bool('') >> flase 布尔值
g = type(a) # 类型
控制语句
# 判断语句
if a > b: # 大于
print('a is greater than b')
elif a < b: # 小于
print('a is less than b')
else: # 等于
print('a is equal to b')
# 循环语句
for i in range(10): # 范围
print(i) # >> 0 1 2 3 4 5 6 7 8 9
# while循环
while a < 10: # 循环
print(a)
a += 1
# 循环嵌套
while a < 10:
print(a)
a += 1
if a == 5:
break
else:
continue
内置函数
# 常用内置函数
print(len([1, 2, 3])) # 3
print(max(1, 2, 3)) # 3
print(min(1, 2, 3)) # 1
print(sum([1, 2, 3])) # 6
print(abs(-5)) # 5
print(round(3.14159, 2)) # 3.14
print(sorted([3, 1, 2])) # [1, 2, 3]
print(reversed([1, 2, 3])) # [3, 2, 1]
print(enumerate(['a', 'b', 'c'])) # [(0, 'a'), (1, 'b'), (2, 'c')]
print(zip(['a', 'b', 'c'], [1, 2, 3])) # [('a', 1), ('b', 2), ('c', 3)]
h = dir(a) # 属性
i = len(a) # 长度
n = range(10) # 范围
x = pow(a, b) # 幂运算
bb = hex(a) # 十六进制
cc = oct(a) # 八进制
dd = bin(a) # 二进制
ee = chr(a) # 字符
ff = ord(a) # 字符代码
hh = hash(a) # 哈希值
jj = isinstance(a, int) # 是否是整数
kk = issubclass(a, int) # 是否是整数的子类
ll = callable(a) # 是否可调用
mm = eval(a) # 执行表达式
nn = exec(a) # 执行脚本
oo = compile(a, '<string>', 'exec') # 编译脚本
pp = globals() # 全局变量
qq = locals() # 局部变量
rr = vars() # 局部变量
ss = input() # 输入
函数
# 函数定义
def add(a, b):
return a + b
# 函数多返回值
def add(a, b):
return a + b, a - b
result = add(1, 2)
print(result) # >> (3, -1)
# lambda表达式
add = lambda a, b: a + b
print(add(1, 2)) # >> 3
square = lambda x: x ** 2
print(square(3)) # >> 9
pairs = [(4, 'apple'), (5, 'banana'), (6, 'cherry')]
pairs.sort(key=lambda x: x[0]) # 排序
print(pairs) # >> [(4, 'apple'), (5, 'banana'), (6, 'cherry')]
# 闭包
def outer(a):
def inner(b):
return a + b
return inner
f = outer(1)
print(f(2)) # >> 3
# 函数装饰器
def my_decorator(func):
def wrapper():
print("装饰器前操作")
func()
print("装饰器后操作")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
类
class Person:
# 类属性
species = "Homo sapiens"
# 初始化方法
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
# 实例方法
def greet(self):
return f"Hello, my name is {self.name}"
# 类方法
@classmethod
def get_species(cls):
return cls.species
# 静态方法
@staticmethod
def is_adult(age):
return age >= 18
# 创建实例
p = Person("Alice", 25)
# 调用方法
print(p.greet())
print(Person.get_species())
print(Person.is_adult(20))
高级特性
- 推导式
# 列表推导式
squares = [x**2 for x in range(10)]
# 字典推导式
square_dict = {x: x**2 for x in range(5)}
# 集合推导式
unique_letters = {char for char in 'abracadabra' if char not in 'abc'}
# 生成器表达式
gen = (x**2 for x in range(10))
- 迭代器与生成器
# 迭代器
my_list = [1, 2, 3]
my_iter = iter(my_list)
print(next(my_iter)) # 1
# 生成器函数
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
counter = count_up_to(5)
print(next(counter)) # 1
- with语句
# with语句用于资源管理
with open('file.txt', 'r') as f:
content = f.read()
# 文件会自动关闭
# 自定义上下文管理器
class ManagedFile:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename, 'r')
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
with ManagedFile('file.txt') as f:
content = f.read()
常用操作
异常处理
try:
# 尝试执行可能出错的代码
result = 10 / 0
except ZeroDivisionError:
# 处理特定异常
print("不能除以零!")
except Exception as e:
# 处理其他异常
print(f"发生错误: {e}")
else:
# 没有异常时执行
print("计算成功")
finally:
# 无论是否有异常都会执行
print("执行完毕")
文件操作
# 打开文件
with open("test.txt", "r") as f:
# 读取文件内容
content = f.read()
print(content)
# 写入文件
with open("test.txt", "w") as f:
# 写入文件内容
f.write("Hello World")
print("写入成功")
# 删除文件
os.remove("test.txt")
# 文件夹操作
os.mkdir("test") # 创建文件夹
os.rmdir("test") # 删除文件夹
os.path.exists("test") # 检查文件夹是否存在
正则表达式
import re
text = 'hello world'
pattern = r'hello' # 绝对匹配字符串
replacement = 'goodbye'
new_text = re.sub(pattern, replacement, text)
print(new_text) # >> goodbye world
pattern = r'\s' # 空格
new_text = re.split(pattern, text)
print(new_text) # >> ['hello', 'world']
# 正则表达式匹配
text = 'hello world'
pattern = r'hello'
if re.match(pattern, text):
print('匹配成功')
else:
print('匹配失败')
# 正则表达式匹配
text = 'hello world'
pattern = r'hello'
ans = re.search(pattern, text)
if ans:
print('匹配成功')
ans.group() # >> hello
else:
print('匹配失败')
text = 'The rain in Spain falls mainly on the plain.'
res = re.findall('ai', text)
print(res) # >> ['ai', 'ai', 'ai', 'ai']
json
import json
# 将Python对象转换为JSON字符串
data = {'name': 'John', 'age': 30}
json_str = json.dumps(data)
# 将JSON字符串转换为Python对象
python_obj = json.loads(json_str)
# 读写JSON文件
with open('data.json', 'w') as f:
json.dump(data, f)
with open('data.json', 'r') as f:
loaded_data = json.load(f)
日期时间
from datetime import datetime, timedelta
now = datetime.now() # 当前时间
print(now)
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 格式化时间
tomorrow = now + timedelta(days=1) # 时间运算
requests
import requests
url = 'https://www.baidu.com'
response = requests.get(url)
print(response.status_code) # 200
print(response.text) # >> <!DOCTYPE html>
# POST请求
data = {'key': 'value'}
response = requests.post('https://httpbin.org/post', data=data)
print(response.status_code) # 200
print(response.json()) # json序列化输出
urllib3
import urllib3
http = urllib3.PoolManager()
response = http.request('GET', 'https://www.baidu.com')
print(response.status) # 200
print(response.data) # >> <!DOCTYPE html>
random
import random
# 随机整数
print(random.randint(1, 10))
# 随机浮点数
print(random.random()) # 0-1之间
# 随机选择
colors = ['red', 'green', 'blue']
print(random.choice(colors))
# 打乱顺序
random.shuffle(colors)
其它
python源与环境配置
windows在C:\Users\Sangfor\pip目录下新建一个pip.ini文件,内容如下:
[global]
# 从清华大学镜像源 https://pypi.tuna.tsinghua.edu.cn 代理, 缓存1天
index-url = <开源>
# 内部私有pypi服务
extra-index-url = <开源>
[install]
trusted-host = <host>
- 或者直接指定源来安装,如:
python -m pip install -i <开源> --trusted-host mirrors.sangfor.org --upgrade pip
pip install -i <开源> --trusted-host mirrors.sangfor.org pyarmor
Python3 环境配置
1.Centos安装python3 >>yum install python3
2.配置pip源 >> cat .pip/pip.conf
[global]
# 从清华大学镜像源 https://pypi.tuna.tsinghua.edu.cn 代理, 缓存1天
index-url = https://pypi.tuna.tsinghua.edu.cn
# 内部私有pypi服务
extra-index-url = https://pypi.tuna.tsinghua.edu.cn
[install]
trusted-host =<host>
3 更新pip3
4.也可以直接指定源来安装,如:jinja2
pip3 install -i <开源> --trusted-host <host> jinja2
python2离线安装pip
1. 先安装setuptools
wget https://pypi.python.org/packages/45/29/8814bf414e7cd1031e1a3c8a4169218376e284ea2553cc0822a6ea1c2d78/setuptools-36.6.0.zip#md5=74663b15117d9a2cc5295d76011e6fd1
unzip setuptools-36.6.0.zip
cd setuptools-36.6.0
python setup.py install
2. 安装pip
wget https://pypi.python.org/packages/11/b6/abcb525026a4be042b486df43905d6893fb04f05aac21c32c638e939e447/pip-9.0.1.tar.gz#md5=35f01da33009719497f01a4ba69d63c9
tar -zxvf pip-9.0.1.tar.gz
cd pip-9.0.1
python setup.py install