Python 基础知识
大约 16 分钟
Python 基础知识
Python速览
1. 注释
- 单行注释:以#开头,注释内容直到行尾。
- 多行注释:用三个单引号或三个双引号括起来的注释内容。
# 这是一个单行注释
print("Hello, World!") # 这是一个单行注释
# 多行注释
"""
1. 注释1
2. 注释2
"""
2. 数字
- 运算符:+、-、*、/(带小书)、//(整除,剔除小数)、%(取余)。
- **:幂运算,例如 2 ** 3 等于 2 的 3 次方,即 8。
- 混合运算会将结果转为浮点型。
3. 文本(字符串)
- 字符串:用单引号或双引号括起来的文本。
- 转义字符:用反斜杠\开头的特殊字符,例如\n 表示换行符,\t 表示制表符等,例如'doesn't' => doesn't。
- 跨行字符
# 字符跨行 print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """) - 字符串拼接:
- +:将两个字符串拼接起来,例如"Hello" + "World" => "HelloWorld"。
- _:将字符串重复多次,例如"Hello" _ 3 => "HelloHelloHello"。
- 相邻字符串会自动拼接,例如"Hello" "World" => "HelloWorld"。
- 字符串支持索引访问,例如"Hello"[0] => "H","Hello"[-1] => "o",以此类推。索引越界时会报错。
# 索引访问 userName = "sunshine" print("userName[0]", userName[0]) # 第一位s print("userName[-0]", userName[-0]) # 第一位s,-0和0效果一致 print("userName[-1]", userName[-1]) # 最后一位e ``` - 字符串切片,越界时切片会自动处理。
# 切片 print("userName 1~2", userName[:2]) # 从0到2(不含)位置的字符,su print("userName 2~5", userName[2:5]) # 从2到5(不含)位置的字符,nsh print("userName -2", userName[-2:]) # 从倒数第二个(含)到末尾,ne print("s[:i] + s[i:] 总是等于 s", userName[:2] + userName[2:]) # sunshine - 字符串不可修改,例如"Hello"[0] = "h"会报错,要想修改字符串,只能创建新的字符串。
- 字符串长度:len("Hello") => 5
4. 列表
python 中的列表是用方括号[]括起来的,元素之间用逗号隔开。列表中可包含不同类型的元素,但是通常情况下各个元素类型相同。
- 列表的定义:
# 列表的定义 list1 = [1, 2, 3, 4, 5] list2 = ["a", "b", "c", "d", "e"] list3 = [1, "a", True, 3.14, None] - 列表切片:切片会返回新的列表,不会修改原列表。
# 列表切片 squares = [1, 4, 9, 16, 25] print("list1 1~2", squares[1:3]) # 从1到3(不含)位置的元素,[4, 9] print("list2 -2~", squares[-2:]) # 从倒数第二个(含)到末尾,[16, 25] - 列表合并:
# 列表合并 list4 = list1 + list2 # [1, 2, 3, 4, 5, 'a', 'b', 'c', 'd', 'e'] - 列表值替换:
# 列表值替换 squares[0] = 100 # [100, 4, 9, 16, 25] - 插入新数据:
# 插入新数据 squares.insert(2, 36) # 在索引为2的位置插入数据36 print("squares:", squares) # squares: [1, 4, 36, 9, 16, 25] # 末尾插入 squares.append(77) print("squares:", squares) # squares: [1, 4, 36, 9, 16, 25, 77] - 列表长度:len(squares) => 7
- 列表可以嵌套列表,例如:
# 嵌套列表 nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print("nested_list[0]", nested_list[0]) # [1, 2, 3]
流程控制
if 语句:根据条件判断是否执行某些代码。if 语句后可有 0 个或多个 elif 语句,最后可跟 0 个或 1 个 else 语句。
# if、elif、else语句 age = 18 if age >= 18: print("成年人") elif age >= 12: print("青少年") else: print("未成年人")for 语句:用于遍历序列(如列表、元组、字符串等)中的每个元素。
# 常规循环 words = ['cat', 'window', 'defenestrate'] for word in words: print(word, len(word)) """ cat 3 window 6 defenestrate 12 """ # 循环对象 users = { 'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active' } for user,status in users.copy().items(): # 操作修改时,提前copy一份进行for print(user) if status == 'active': print(user) else: del users[user] print(users)range()函数:用于生成一个整数序列,通常用于 for 循环中。
# range()函数 for i in range(5): print(i) print("------") # 指定数字开始 for i in list(range(3, 8)): # 生成[3,8)列表 print(i) # 3 4 5 6 7 print("------") # 指定步长 for i in list(range(3, 8, 2)): # 生成范围[3,8),步长为2的列表 print(i) # 3 5 7break 和 continue 语句
- break 语句:用于跳出当前最近的一个循环,不再执行后续循环。
- continue 语句:用于跳过当前循环的剩余代码,直接进入下一次循环。
# break for i in list(range(1, 10)): if i % 3 == 0: break print(i) # 1 2 # continue for i in list(range(1, 10)): if i % 3 == 0: continue print(i) # 1 2 4 5 7 8循环的 else 子句
在 for 或 while 循环中,break 语句可能对应一个 else 子句,若循环在未执行 break 的情况下结束,else 子句将会被执行。
# 循环中的else,例如找质数
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n // x)
break
else:
print(n, 'is not equals')
- pass 语句:不执行任何动作
# pass语句
for i in list(range(1, 10)):
if i % 3 == 0:
pass
else:
print(i) # 1 2 4 5 7 8
while True:
pass # 无限等待键盘中断 (Ctrl+C)
- match:类似于 js 中的 switch 语句,用于根据不同的情况执行不同的代码块。
# match语句
def http_error(status):
match status:
case 400:
return 'Bad Request'
case 429:
return 'Too Many Requests'
case 500:
return 'Internal Server Error'
case 401 | 403 | 404: # 组合
return 'Not Found'
case _:
return 'Server Error'
- 定义函数:函数关键字 def
# 1. 默认值函数:默认值参数需在最后面
def defaultAruguments(prompt, render=4):
print(prompt)
print(render)
defaultAruguments('text');
print("-----2.关键字函数-----")
def keyFunction(voltage, state='online', mode='self'):
print(voltage)
print(state)
print(mode)
# 调用时使用关键字赋值
keyFunction(17, mode='ems', state='offline')
# 特殊符号,*接收任意数量的位置参数,**接收任意数量的关键字参数
def foo(foo1, foo2=10, *args, **kwargs):
print(foo1) # 1
print(foo2) # 2
print(args) # (3,4)
print(kwargs) # {'e': 5, 'f': 6, 'g': 7}
foo(1, 2, 3, 4, e=5, f=6, g=7)
函数定义详解:
- 特殊参数:*、/
- 斜杠/:仅限位置参数,在/左侧的参数只能使用位置参数的方式进行传递。
- 星号*:仅限关键字参数,在*右侧的参数必须使用关键字参数的方式进行传递。
- 组合使用/和*:/左侧的参数只能使用位置参数的方式进行传递,*右侧的参数必须使用关键字参数的方式进行传递。
# 3.特殊参数函数:*、\ def spacialFunction(interable, /, *, key=None, reverse=False): # interable只能位置传参,ke、reverse只能以关键字传参 print(interable) # 位置传参:[1, 2, 3, 4, 5, 6] print(key) # 关键字传参:key print(reverse) # 默认值:False spacialFunction([1, 2, 3, 4, 5, 6], key='key')- 任意实参列表
# 任意实参列表 def concat(*args, sep="/"): return sep.join(args) result = concat("earth", "mars", "venus") print(result) # earth/mars/venus- 解包实参列表
# 解包实参列表 def parrot(voltage, state='a stiff', action='voom'): print("-- This parrot wouldn't", action, end=' ') print("if you put", voltage, "volts through it.", end=' ') print("E's", state, "!") d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"} parrot(**d) # d字典传入,使用**d解包- Lambda 表达式:用于创建小巧的匿名函数
# lambda:创建匿名函数 def make_incrementor(n): return lambda x: x + n f = make_incrementor(42) f1 = f(1) print(f1) # 43文档字符串:用于描述函数的作用、参数、返回值等信息。
函数注解:标注 是以字典形式存放在函数的 ** annotations ** 属性中
def f(ham: str, eggs: str = 'eggs') -> str: print("Annotations:", f.__annotations__) print("Arguments:", ham, eggs) return ham + ' and ' + eggs f('spam')- 特殊参数:*、/
数据结构
1. 列表详解
- list.append(x):向列表末尾添加一项
- list.extent(interable):通过添加来自interable中的所有项来扩展列表。
- list.insert(i, x):在索引 i 位置插入项 x。
- list.remove(x):删除列表中第一个值为 x 的项。如果没有这样的项,将引发 ValueError 异常。
- list.pop([i]):删除索引 i 位置的项,并 返回该项。如果未指定索引,将删除并返回列表的最后一项。
- list.clear():删除列表中的所有项。
- list.index(x[, start[, end]]):返回列表中第一个值为 x 的项的索引。如果没有这样的项,将引发 ValueError 异常。start和end为可选参数,用于指定搜索的范围。
- list.count(x):返回列表中值为 x 的项的数量。
- list.sort(*, key=None, reverse=False):对列表中的项进行排序。
- list.reverse():将列表中的项反转。
- list.copy():返回列表的浅拷贝。
# 列表
ages = [1, 2, 3, 4, 5]
counts = [12, 32, 11]
ages.append(6)
print("append:向列表末尾添加元素", ages)
ages.extend(counts)
print("extend:融合其他列表", ages)
ages.insert(1, 10)
print("insert:在指定索引位置插入元素", ages)
ages.remove(1)
print("remove:移除指定元素", ages)
ages.pop() # 未指定位置时,移出最后一位
print("pop:移除最后一位", ages)
firstIndex = ages.index(4, 2) # 返回元素第一次出现的索引,也可从指定位置开始
print("index:返回查询的元素第一次出现索引:", firstIndex)
numberCount = ages.count(2)
print("count:查询元素出现的次数", numberCount)
ages.sort() # 排序列表元素
print("sort:排序列表,默认从小到大", ages)
ages.reverse() # 反转列表元素
print("reverse:反转数组", ages)
agesCopy = ages.copy()
print("copy:浅拷贝列表", agesCopy)
ages.clear()
print("clear:清空列表", ages)
2. del语句
del语句用于删除列表中的项或变量。
# del语句
ages = [1, 2, 3, 4, 5]
print("删除索引为2的元素:", ages)
del ages[2]
print(ages)
# 删除整个变量
del ages
print("删除整个变量ages:", ages) # 此时会报错,提示ages未定义
3. 元组和序列
元组是不可变的序列,通常用于存储不同类型的元素。
# 元组:由多个用逗号隔开的值组成,元组不可变。
t = 1, True, "时游"
print(t) # (1, True, '时游')
# 嵌套元组
u = t, (111, 222)
print(u) # ((1, True, '时游'), (111, 222))
# 元组不可变
# u[0] = 111 TypeError: 'tuple' object does not support item assignment
# 序列解包:序列解包时,左侧数量应当和右侧一致
a, b, c = t
print(a, b, c) # 1 True 时游
4. 集合
集合是无序的、不重复的元素集合。
# 集合:不重复元素组成的无序多项集,基本用法包括成员检测和消除重复元素。
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket) # 自动移除重复项 {'pear', 'orange', 'banana', 'apple'}
# 交、并、差
a = set('abracadabra')
b = set('alacazam')
diffA = a - b # 存在于 a 中但不存在于 b 中的字母
print("a中存在,b中不存在:", diffA) # {'r', 'd', 'b'}
both = a | b
print("a和b中元素合集(去重后):", both) # {'m', 'r', 'l', 'a', 'z', 'c', 'b', 'd'}
same = a & b
print("a和b中同时存在:", same) # {'a', 'c'}
5. 字典
# 字典:键值对组合
person = {
"name": "时游",
"age": 28,
"country": "CN"
}
print(person) # {'name': '时游', 'age': 28, 'country': 'CN'}
# 查询
print(person.get("name")) # 时游
# 修改值
person["age"] = 30 # {'name': '时游', 'age': 30, 'country': 'CN'}
print(person)
# 删除
del person["age"]
print(person) # {'name': '时游', 'country': 'CN'}
# 返回键列表:返回该字典中所有键的列表
personList = list(person)
print(personList) # ['name', 'country']
# 判断键是否存在
print('age' in person) # False
# 循环
for key, v in person.items():
print(key, v) # name 时游、 country CN
6. 循环技巧
# 循环
# 字典循环
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
print(k, v)
# 列表循环,同时取出索引
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
# 同时循环多个列表,使用zip函数
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print('What is your {0}? It is {1}.'.format(q, a))
模块
# 引入指定目录中的模块
from modules.fb import fib as fb
# as 重命名
fb(500)
1. 标准模块
# 标准库
import sys
# 标准库
print('当前python版本:', sys.version)
2. dir()函数
dir()函数返回模块、类、实例或任何其他对象的属性列表。
# dir函数:返回sys模块的所有属性列表
print(dir(sys))
输入输出
import json
# 格式化字符串字面量
year = 2026
event = "Referendum"
# 在字符串前加f或F,即可使用变量
print(f'Results of the {year} {event}')
# str.format()方法
print("今年是{}年".format(year)) # 今年是2026年
print('{1} and {0}'.format('spam', 'eggs')) # eggs and spam
print('This {food} is {adjective}.'.format(
food='spam', adjective='absolutely horrible')) # This spam is absolutely horrible.
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
'Dcab: {0[Dcab]:d}'.format(table)) # Jack: 4098; Sjoerd: 4127; Dcab: 8637678
for x in range(1, 11):
print('{0:d} {1:d} {2:d}'.format(x, x * x, x * x * x))
# 读写文件
# open('workfile', 'w', encoding="utf-8"),第一个参数是文件名,第二个参数为对文件的权限,第三个参数为编码格式,通常utf-8
# 1. windows上结束符为\n,Linux上为\n
# 2. 处理文件最好使用with关键字,子句结束后会自动关闭文件
with open('file.txt', 'w+', encoding='utf-8') as f:
tell1 = f.tell()
print('tell1:', tell1)
# 读取整个文件数据
# content = f.read() # 参数size可选,省略或为负数时返回整个文件的内容;size为其他值时,读取并返回最多size个字符。若已到文件末尾,返回''。
# print('全文件内容:', content)
# 读取单行数据
# lineData = f.readline()
# print('第一行内容:', lineData)
# 循环读取行数据
# for lin in f:
# print(lin)
# 写入
f.write('hello world\n')
# 写入之前需转为字符串
value = ('the answer', 42)
s = str(value) # 将元组转换为字符串
f.write(s)
# f.tell():当前指针位置
tell = f.tell()
print('tell:', tell)
# f.seek(offset, whence):修改指针位置,offset表示移动量,whence:为 0 时,表示从文件开头计算,1 表示使用当前文件位置,2 表示使用文件末尾作为参考点
f.seek(1)
f.write('第一\n') # 从索引1开始写入
# JSON格式化
x = [1, 'simple', 'list']
f.write(json.dumps(x))
print("JSON格式化:", json.dumps(x))
print("反序列化:", json.loads(json.dumps(x))[1]) # simple
# 关闭文件流
f.close()
错误与异常
暂时略过
类
类提供了把数据和功能绑定在一起的方法,类的实例化会创建一个新的对象,每个对象都有自己的属性和方法。
名称与对象
对象之间相互独立,多个名称(甚至是多个作用域内的多个名称)可以绑定到同一对象。
Python 作用域和命名空间
命名空间是一个从名称到对象的映射。在 Python 中,每个模块、类或函数都有自己的命名空间。命名空间的作用是避免名称冲突,使代码更加清晰和可维护。
类的定义
class MyClass:
"""一个简单的类示例"""
i = 12345
def f(self):
return 'hello world'
类属性与方法
# 类:类提供了把数据和功能绑定在一起的方法
# 作用域
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam # nonlocal:声明为最近外层的局部变量
spam = "nonlocal spam"
def do_global():
global spam # global:声明为全局变量
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam) # test spam
do_nonlocal()
print("After nonlocal assignment:", spam) # nonlocal spam
do_global()
print("After global assignment:", spam) # nonlocal
scope_test()
print("In global scope:", spam) # global spam
# 类
class Animal:
# 颜色:公共属性,会被所有子对象共用
colors = []
# 赋初始值,类似于js中的constructor
def __init__(self, name):
self.name = name
self.skills = [] # 每个实例独有属性
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
# 添加颜色
def set_color(self, color):
self.colors.append(color)
# 添加能力
def set_skill(self, skill):
self.skills.append(skill)
# 间隔符号
def add_logs(self):
print("-------------")
# 调用自身函数
def classTest(self):
self.add_logs()
# 创建dog实例
dog = Animal("Dog")
dog.set_name("旺财")
dog.set_skill("汪汪汪")
print(dog.get_name()) # 旺财
print(dog.skills) # ['汪汪汪']
# 创建cat实例
cat = Animal("Cat")
cat.set_name("Tom")
cat.set_color("orange")
print(dog.colors) # ['orange']
print(cat.colors) # ['orange']
cat.set_skill("喵喵喵")
print(cat.skills) # ['喵喵喵']
cat.classTest()
类继承
# 继承
class Device:
def __init__(self, device_name, device_code):
self.device_name = device_name
self.device_code = device_code
def get_device_info(self):
return {
"device_name": self.device_name,
"device_code": self.device_code
}
class EMS(Device): # 继承Device类
def __init__(self, device_name, device_code):
super().__init__(device_name, device_code)
def set_ems_power(self, power):
self.ems_power = power
ems = EMS('EMS', 'EMS-0001')
device_info = ems.get_device_info()
print(device_info)
私有变量
python中不存在私有属性,但是可以通过约定来定义。
# 私有属性:仅限从一个对象内部访问的“私有”实例变量在 Python 中并不存在。Python 代码都遵循这样一个约定:带有一个下划线的名称 (例如 _spam) 应该被当作是非公有部分
class Bird:
def __init__(self, name, age):
self.name = name
self.age = age
self._colors = [] # 遵守约定,_colors为私有属性,同理,函数也一致
def set_color(self, color):
self._colors.append(color)
bird1 = Bird("Bird1", "Bird-0001")
bird1.set_color("blue")
print(bird1._colors)
bord2 = Bird("Bord2", "Bord-0002")
bord2.set_color("red")
print(bord2._colors)
标准库
import os
import shutil
import glob
import sys
import argparse # 提供了一种更复杂的机制处理命令行参数
import re # 提供正则表达式工具
import math # 提供数学函数
import random # 随机数
import statistics # 基本的统计
from urllib.request import urlopen # 从url检索数据
from datetime import date # 操作日期和时间
import zlib # 压缩库
# os库:提供了很多操作系统交互的函数
print(os.getcwd()) # 返回当前目录
print(dir(os)) # 返回由模块的所有函数组成的列表
# 调用系统命令
os.system("ls") # 可执行系统命令
# os.system("mkdir files") # 可执行系统命令
# shutil库:提供文件和目录管理接口
shutil.copyfile('file.txt', 'dataCopy.txt') # 拷贝文件,目标文件不存在时会创建
# shutil.move('dataCopy.txt','files') # 移动文件,目标文件夹中存在时会报错
# global库:查询文件
print(glob.glob('*.py')) # ['类.py', '输入输出.py', 'main.py', '标准库.py']
# sys库:命令行参数存储于sys的argv属性中
print(sys.argv) # 获取执行python时的命令行参数,例如python3 demo.py one two three,会打印['demo.py', 'one', 'two', 'three']
# parser = argparse.ArgumentParser(
# prog='top',
# description='Show top lines from each file')
# parser.add_argument('filenames', nargs='+')
# parser.add_argument('-l', '--lines', type=int, default=10)
# args = parser.parse_args()
# print(args)
# 终止脚本:exit()
# sys.exit()
# re库:提供正则表达式处理
filter_str = re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
print(filter_str) # ['foot', 'fell', 'fastest']
# math库:数学工具函数
cos = math.cos(math.pi / 2) # 6.123233995736766e-17
print(cos)
sin = math.sin(math.pi / 2) # 1
print(sin)
log = math.log(1024, 2)
print(log) # 10
# random库:随机数
number1 = random.random()
print("random:", number1) # [0.0, 1.0)中的浮点随机数
ls = random.sample(range(0, 100), 10) # 无重复值的10个随机数
print("sample:", ls) # 随机10个数字
rg = random.randrange(6)
print("rg:", rg)
# statistic库:基本的统计属性
data = [1, 2, 3]
avg_number = statistics.mean(data)
print("均值:", avg_number) # 均值: 2
mid_number = statistics.median(data)
print("中位数:", mid_number) # 中位数: 2
var_number = statistics.variance(data)
print("方差:", var_number) # 方差: 1
# 获取网页
with urlopen('https://www.baidu.com/') as response:
html = response.read()
# 写入文件中
with open('baidu.html', 'wb') as f:
f.write(html)
f.close()
print(html)
# datetime库:操作日期和时间
now = date.today()
print("今天日期:", now.today()) # 今天日期: 2026-01-23
print("年份:", now.year) # 时间: 2026
print("月份:", now.month) # 时间: 1
# zip库:数据压缩,支持zlib、gzip、bz2、lzma、zipfile、tarfile
s = '测试文本内容'.encode('utf-8')
print(f"原文长度:{len(s)}") # 原文长度:41
print(f"原文:{s.decode('utf-8')}")
t = zlib.compress(s)
print(f"压缩后长度:{len(t)}") # 压缩后长度:37
print(f"压缩后:{t}")
rt = zlib.decompress(t)
print(f"解压缩后:{rt.decode('utf-8')}") # 测试文本内容
Loading...
