📚 Python语言的特点
- ✅ 简单易学
- ✅ 免费开源
- ✅ 面向对象
- ✅ 可移植性
- ✅ 可扩展性
- ✅ 丰富的库
- ✅ 规范的代码
- ✅ 动态语言特点
🏷️ 变量命名
命名惯例
| 命名法 | 示例 | 说明 |
|---|
| 大驼峰命名法 | RssReader | 每个单词首字母大写 |
| 小驼峰命名法 | rssReader | 第一个单词首字母小写 |
| 蛇形命名法 | rss_reader | Python推荐,单词小写用下划线连接 |
命名规则
- ❌ 变量名不能以数字开头
- ⚠️ 变量名区分大小写 (
total ≠ Total) - 🔒 双下划线开头的变量为私有变量
2cats = 10 # 错误
_cats = 10 # 可以
hey@hey = 10 # 不推荐
cats != CATS # 大小写不同
📦 数据类型
| 类型 | 说明 | 示例 |
|---|
bool | 布尔值 | True, False |
int | 整数 | 1, 2, 3 |
float | 浮点型 | 1.0, 2.0 |
str | 字符串 | 'hello world' |
list | 列表(可修改) | [1, 'apple', 10.5] |
tuple | 元组(不可修改) | (1, 'apple', 10.5) |
dict | 字典 | {'name':'john', 'address':'xyz street'} |
set | 集合(不重复) | {1, 'apple', 10.5} |
frozenset | 不可变集合 | frozenset({1, 'apple', 10.5}) |
# 布尔值
x = True
# 整数
y = 1
# 字符串
z = "Hello World"
# 列表
numbers = [1, 2, 3, 'four']
# 元组
letters = ('a', 'b', 'c', 'd')
🔤 字符串详解
字符串定义
str1 = 'Hello, world!'
str2 = "Hello, world!"
str3 = '''Hello,
world!'''
str4 = """Hello,
world!"""
字符串格式化
miles = "10"
print('%s %s' % ('Hello', 'world'))
print('只有一个{}*'.format(1,2)) # 默认占位
print('{0}*{0}+{1}'.format(1,2)) # 数字占位
print('{a1}*{a1}+{a2}'.format(a1=2,a2=3)) # 参数占位
print("Today you ran {0} miles. Good Job".format(miles))
print(f"Today you ran {miles} miles. Good Job") # f-string格式化
原始字符串和字节串
# 原始字符串 (r前缀)
my_string_r = r'\nTest\n' # 转义字符不生效
# 字节串 (b前缀)
my_string_b = b'hello' # 字节序列
编码转换
# 字符转Unicode编码
hex(ord('中')) # '0x4e2d'
# 字符转UTF-8编码
'中'.encode('utf-8') # b'\xe4\xb8\xad'
# Unicode编码还原成字符
chr(0x4e2d) # '中'
# UTF-8编码还原成字符
b'\xe4\xb8\xad'.decode('utf-8') # '中'
🔍 正则表达式
常用元字符
| 元字符 | 说明 |
|---|
\d | 匹配数字 |
\D | 匹配非数字 |
\w | 匹配字母、数字、下划线 |
\s | 匹配空白字符 |
^ | 匹配字符串开头 |
$ | 匹配字符串结尾 |
. | 匹配任意字符(除换行符) |
* | 匹配0次或多次 |
+ | 匹配1次或多次 |
? | 匹配0次或1次 |
常用匹配模式
import re
# 匹配邮政编码
postcode = '100101'
pattern = r'\d{6}'
result = re.match(pattern, postcode)
# 匹配身份证号码
idcard = '110101199001011234'
pattern = r'\d{17}[\dXx]'
result = re.search(pattern, idcard)
# 匹配手机号码
phone = '13912345678'
pattern = r'1\d{10}'
result = re.search(pattern, phone)
# 匹配邮箱地址
email = 'abc@xyz.com, def@xyz.com'
pattern = r'\w+@\w+\.[a-z]{2,3}'
result = re.findall(pattern, email)
# 替换字符串
text = 'Hello, world!'
pattern = r'world'
result = re.sub(pattern, 'Python', text)
➕ 运算符
算术运算符
print(10*2) # 乘法
print(10**2) # 平方
print(10/2) # 除法(返回浮点数)
print(10//2) # 整除
print(10%2) # 取模
比较运算符
print(10>2) # 大于
print(10<2) # 小于
print(10>=2) # 大于等于
print(10<=2) # 小于等于
print(10==2) # 等于
print(10!=2) # 不等于
逻辑运算符
a = 0
if a and a == 2 and a > 10:
print("条件都为True")
if a or b:
print("至少一个为True")
if not(a and b):
print("取反")
成员运算符
a = 10
list = [1, 2, 3, 4, 5]
if a in list:
print("a在列表中")
if a not in list:
print("a不在列表中")
身份运算符
a = [1,2,3]
b = [1,2,3]
print(a == b) # True - 值相等
print(a is b) # False - 不是同一对象
🔀 条件语句
from random import *
x = randint(1,20)
if x < 18:
print('Sorry You are too young')
elif x >= 18 and x <= 21:
print('You are allowed to go')
else:
print('You are old enough for this')
🔄 循环语句
while循环
import random
min = 1
max = 6
roll_again = "yes"
while roll_again in ("yes", "y"):
print("Rolling the dices...")
print(random.randint(min, max))
roll_again = input("Roll again?").strip().lower()
for循环
for x in range(1,10):
if x == 9:
break
elif x == 5:
continue
else:
print(x)
📋 列表操作
shopping_list = []
shopping_list.append("item")
shopping_list.extend([5,6,7,8])
shopping_list.insert(1, 'hi')
shopping_list.pop()
shopping_list.remove(1)
shopping_list.reverse()
shopping_list.sort()
# 切片
x = [1,2,3,4,5,6]
print(x[0:2]) # [1,2]
print(x[0:7:2]) # [1,3,5]
# 列表推导式
y = [x*x for x in range(10) if x%2==0]
📦 元组操作
x = (1,2,3,4,5)
x.count(1) # 统计出现次数
x.index(1) # 查找索引
📖 字典操作
info = {
'name': 'John',
'city': 'New York',
'own_a_car': True,
}
print(info.get('name'))
print(info['name'])
for key, value in info.items():
print(key, value)
# 字典推导式
a = dict(a=1,b=2,c=3)
b = {key: value**2 for key, value in a.items()}
🎯 集合操作
my_set = {1, 'apple', 10.5}
my_set.add('banana')
my_set.remove('apple')
my_set.discard('apple') # 不存在不报错
a = {1,2,3,4}
b = {2,3,5}
print(a | b) # 并集
print(a & b) # 交集
# 不可变集合
my_frozen_set = frozenset(my_set)
🛠️ 函数定义
基本函数
def elo(player_rating, opponent_rating, won, k=32):
q1 = 10**(player_rating / 400)
q2 = 10**(opponent_rating / 400)
expected_score = q1 / (q1 + q2)
true_score = int(won)
final_score = player_rating + k * (true_score - expected_score)
return int(final_score)
位置参数和关键字参数
def example_function(arg1, arg2, kwarg=None):
print(f"arg1: {arg1}")
print(f"arg2: {arg2}")
if kwarg:
print(f"kwarg: {kwarg}")
example_function("a", "b")
example_function("a", "b", kwarg="c")
example_function(arg2="b", arg1="a", kwarg="c")
可变参数
def example_function(*args):
for arg in args:
print(arg)
example_function(1, 2, 3)
def example_function(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
example_function(name="Alice", age=30)
参数顺序
# 参数顺序: 位置参数 -> *args -> 默认参数 -> **kwargs
def odering(a, b, *args, name='john', **kwargs):
return [a, b, args, name, kwargs]
🔄 迭代器
from collections.abc import Iterable, Iterator
# 判断是否可迭代
isinstance([], Iterable) # True
isinstance({}, Iterable) # True
isinstance('abc', Iterable) # True
# 判断是否是迭代器
isinstance([], Iterator) # False
isinstance(iter([]), Iterator) # True
⚠️ 异常处理
try:
x = int(input("Enter a number"))
except ValueError:
print("Enter a valid Number")
except:
print("Unknown error")
else:
print("Thanks for a valid number")
finally:
print("I will run no matter what")
🐛 PDB调试
常用PDB命令:
l - 列表n - 下一行p - 打印c - 继续