> 文章列表 > python 基础语法记录

python 基础语法记录

python 基础语法记录

Python

注释

  • 单行注释
    #

  • 多行注释
    ‘’’
    ‘’’
    “”"
    “”"

变量的定义

name = 'xr'

数据类型

Number (数字)
int 整形
float 浮点型
complcx 复数

String (字符串)

Boolean (布尔)
True
False

List (列表)

Set (集合)

Tuple (元祖)
numTuple = (1,2,3)

Dictionary(字典)

字符串合并

  • %s 将内容转换为字符串
    %d 将内容转换为整数
    %f 将内容转换为浮点数

f"{name}"

查看数据类型 type()

age = 20
print(type(age))  # <class 'int'>age = 2.0
print(type(age))  # <class 'float'>bool = False
print(type(bool))  # <class 'bool'>userList = ['xr', 'zs']
print(type(userList))  # <class 'list'>numTuple = (1, 2, 3)
print(type(numTuple))  # <class 'tuple'>users = {'name': 'xr'}
print(type(users))  # <class 'dict'>

类型转换

int

a = 2.0
b= int(a)
print(b,type(b)) # 2 <class 'int'>a = True
b= int(a)
print(b,type(b)) # 1 <class 'int'>a = '123'
b= int(a)
print(b,type(b)) # 123 <class 'int'># 错误
a = '123a'
b= int(a)
print(b,type(b)) # ValueError: invalid literal for int() with base 10: '123a'a = '1.23'
b= int(a)
print(b,type(b)) # ValueError: invalid literal for int() with base 10: '1.23'

float

a = 10
b= float(a)
print(b,type(b)) # 10.0 <class 'float'>a = '10'
b= float(a)
print(b,type(b)) # 10.0 <class 'float'>a = True
b= float(a)
print(b,type(b)) # 1.0 <class 'float'>

str

a = 1
b= str(a)
print(b,type(b)) # 1 <class 'str'>a = 1.3
b= str(a)
print(b,type(b)) # 1.3 <class 'str'>a = True
b= str(a)
print(b,type(b)) # True <class 'str'>

bool

# a = 0
# a = 0.0
# a = ''
# a = []
# a = ()
a = {}
b= bool(a)
print(b,type(b)) # False <class 'bool'>

流程控制语句

if elif else

age = 12if age > 18:print('大于18')
elif age < 10:print('小于10')
else:print('大于18小于10之间')

for in

range()

for num in range(6):print(num)
0
1
2
3
4
5
for num in range(2, 6):print(num)
2
3
4
5
for num in range(2, 6, 3):print(num)
2
5
userList = ['小明', '小红']
for user in userList:print(user)
for user in range(len(userList)):print(user)小明
小红
0
1

String

a = 'abcde'# 5
print(len(a))# 1
print(a.find('b'))# 1
print(a.count('c'))a=' abc '
# abc
print(a.strip())a='1,2,3'
# ['1', '2', '3']
print(a.split(','))a='abc'
# ABC
print(a.upper())a='ABC'
# abc
print(a.lower())str = 'abcd'
value = str.replace('b','e')
print(value) # aecd
print(str) # abcd

List 列表

列表的常用方法

查找某元素的下标 index(查找的元素)

list = ['a','b','c']
print(list.index('b')) # 1
print(list.index('d')) # 如果元素不存在会报错 'd' is not in list

修改列表的下标值

list = ['a','b','c']
list[1] = 2
print(list) # ['a', 2, 'c']

插入元素 insert(下标,值)

list = ['a','b','c']
list.insert(3,'d')
print(list) # ['a', 'b', 'c', 'd']

追加元素到尾部 append(值)

list = ['a','b','c']
list.append('d')
print(list) # ['a', 'b', 'c', 'd']

追加多个元素 extend([多个值,…])

list = ['a','b','c']
list.extend(['d','e'])
print(list) # ['a', 'b', 'c', 'd', 'e']

删除元素

# del list[下标]
list = ['a','b','c']
del list[1]
print(list) # ['a', 'c']# pop(下标)
list = ['a','b','c']
ele = list.pop(1)
print(list,ele) # ['a', 'c'] b# remove(删除的值)
list = ['a','b','c']
list.remove('b')
print(list) # ['a', 'c']# 清空列表 clear()
list = ['a','b','c']
list.clear()
print(list) # []

统计某元素出现的次数

list = ['a','b','c','a']
count = list.count('a')
print(count) # 2

统计列表总元素个数

list = ['a','b','c']
length = len(list)
print(length) # 3

判断元素是否在列表中

list = ['a','b','c']
print('a' in list) # True
print('d' in list) # False
print('d' not in list) # True

列表的循环遍历

while

list = ['a','b','c']
index = 0
while index < len(list):print(list[index])index += 1

for in

list = ['a','b','c']
for i in list:print(i)

Tuple 元组

元祖中的数据不能被修改,但是如果嵌套列表则列表里可以修改
如果元祖中只有一个值,那么结尾要加逗号否则是 int 类型

a= (4)
b=(5,)
c=()
# <class 'int'> <class 'tuple'> <class 'tuple'>
print(type(a),type(b),type(c))

元组中的方法 (与列表相同)

index()
count()
len()

元组的遍历

while
for in

序列

序列是指:内容连续,有序,可使用下标索引的一类数据容器
列表、元组、字符串均可视为序列

切片

语法:序列[起始下标(包含,可以写空):结束下标(不包含,可以写空):步长]
切片并不会影响序列,而是创建一个新的数据

a = 'abcdef'
# a
print(a[0])# ab
print(a[0:2])# ab
print(a[:2])# bcdef
print(a[1:])# ac
print(a[0:4:2])

set 集合

集合:是无序的,不是序列,不支持元素的重复

set = {'a','b'}{} 是 字典
空集合需要这样定义
set = set()

常用的方法

添加元素 add(添加的元素)

set = {'a','b','c'}
set.add('d')
print(set) # {'c', 'a', 'd', 'b'}

移除元素 remove(移除的元素)

set = {'a','b','c'}
set.remove('b')
print(set) # {'a', 'c'}

从集合随机取出元素(既删除)

set = {'a', 'b', 'c'}
res = set.pop()
print(res, set)  # c {'a', 'b'}

清空集合

set = {'a', 'b', 'c'}
set.clear()
print(set)  # set()

取出两个集合的差集
语法:集合 1.difference(集合 2)
取出集合 1 和集合 2 的差集(集合 1 有而集合 2 没有的元素),得到一个新的集合,集合 1 集合 2 不变

set1 = {1,2,3}
set2 = {1,4,5}
res = set1.difference(set2)
print(res) # {2, 3}

消除两个集合的差集
语法:集合 1.difference_update(集合 2)
对比集合 1 和集合 2 的,在集合 1 内,删除和集合 2 相同的元素。集合 1 被修改了,集合 2 不变

set1 = {1,2,3}
set2 = {1,4,5}
set1.difference_update(set2)
print(set1,set2) # {2, 3} {1, 4, 5}

两个集合合并

set1 = {1,2,3}
set2 = {1,4,5}
set3 = set1.union(set2)
print(set3) # {1, 2, 3, 4, 5}

统计集合元素数量

set = {1,2,3}
print(len(set)) # 3

循环 不支持 while 循环

for in

dict 字典

常用方法

获取字典的个数

user = {'name': 'xr', 'age': 20}
print(len(user)) # 2

获取 value

user = {"name":"xr","age": 15}
# xr
print(user['name'])# 15
print(user.get('age'))# None
print(user.get('sex'))# KeyError: 'sex'
print(user['sex'])

新增和修改,有则修改,无则新增

user = { "age": 15}
user['name'] = 'xr'
print(user)  # {'age': 15, 'name': 'xr'}

删除

user = {'name': 'xr', 'age': 20}
res = user.pop('name')
print(res) # xr
print(user) # {'age': 20}
user = {'name': 'xr', 'age': 20}
# del user["age"]
# {'name': 'xr'}del user
# 会把字典 user 包括变量整个删除
# NameError: name 'user' is not defined. Did you mean: 'super'?
print(user)
user = {'name': 'xr', 'age': 20}# 清空
user.clear()
# {}
print(user)

循环遍历

user = {'name': 'xr', 'age': 20}for key in user.keys():# name# ageprint(key)for value in user.values():# xr# 20print(value)for key,value in user.items():# name xr# age 20print(key,value)for item in user.items():# ('name', 'xr')# ('age', 20)print(item)

函数

def f():print('1')
f()

函数返回值

def sum(a,b):return a+bres = sum(2,3)
result =  sum(b=3,a=5)
print(res,result)

多个返回值

def f():return 1, 2
x, y = f()
print(x, y)  # 1 2

函数多种参数使用形式

def user(name, age=18):print(f"{name}--{age}")# 位置参数
user('xr', 20)  # xr--20
# 关键字参数
user(age=10, name='zs')  # zs--10
# 缺省参数(默认值)
user('ls')  # ls--18# 不定长参数
def info(*args):print(args) # 合并为元组类型
info() # ()
info('xr') # ('xr',)
def user_info(kwargs):print(kwargs)
# 传递 key=value
user_info(name='xr',age=20) # {'name': 'xr', 'age': 20}

函数作为参数使用

def test(fun):res = fun(1, 2)print(res)def fun(x, y):return x+ytest(fun) # 3

lambda 匿名函数

函数体只能写一行

lambda x,y: x+y
def test(fun):res = fun(1, 3)print(res)test(lambda x, y: x+y)  # 4

函数注释

def add(x,y):"""add 计算两数和:param x::param y::return: 结果"""result = x + yprint(f'x+y: {result}' )return resultadd(1,2)

全局变量局部变量

num = 100
print(num) # 100def init():num = 20  # 此时局部 num 和 全局 num 不是一个变量print(num) # 20init()
print(num) # 100

global 关键字把局部变量设为全局变量

num = 100
print(num) # 100def init():global num  # 设置内部变量为全局变量num = 20print(num) # 20init()
print(num) # 20

文件操作

语法:open(name,mode,encoding)

  • name 打开目标文件名的字符串。可以是绝对路径 “D:/test.txt”
  • mode 设置打开文件的模式
    • r 只读方式打开文件
    • w 打开一个文件用于写,如果文件有内容则会删除原内容并重新写入。如果文件不存在则创建文件
    • a 追加内容,如果文件有内容,新的内容会被写入在原内容后面。如果文件不存在则创建文件 使用 \\n 实现换行符 例: ‘\\n内容’
  • encoding 编码格式

read(num) num 读取文件的长度,没写则读取所有内容

# f = open('test.txt','r',encoding='utf-8')
# print(f.read())# readlines 读取文件的全部行放进列表中,每个值是一行内容
# print(f.readlines())# readline() 读取文件一行
# f.readline()# 循环读取文件
# for line in f:
#     print(line)# 文件关闭
# f.close()# with open 不需要手动关闭
# with open('test.txt') as f:
#     for line in f:
#         print(line)

写/追加

f = open('test.txt','a',encoding='utf-8')
f.write('\\n内容')
f.close()

异常

语法:

try:
可能出现错误的代码
except:
出现异常执行的代码

try:f = open('tests.txt', 'r')
except:print('File not found')

指定异常处理

try:f = open('not.txt', 'r')
except FileNotFoundError as e:print(f"{e}")

捕获多个异常

try:f = open('not.txt', 'r')
except (FileNotFoundError,NameError):print()

捕获所有异常

try:f = open('not.txt', 'r')
except Exception as e:print(e)
else:print('没有出现异常执行的代码')
finally:print('无论成功还是失败都会执行的代码')

模块

使用内置模块

语法:[from 模块名] import [模块|类|变量|函数|*] [ as 别名]

import time
print('11')
time.sleep(2)
print('22')import time as times
print('11')
times.sleep(2)
print('22')

from 模块名 import 功能名

from time import sleep
print('11')
sleep(2)
print('22')from time import sleep as sleeps
print('11')
sleeps(2)
print('22')# 导入 time 所有功能
from time import *
print('11')
sleep(2)
print('22')

自定义模块

新建 custom_module.py 文件

def add(num1, num2):print(num1 + num2)# __main__ 模块引入的时候不会调用下面,只有单独运行此文件才会执行
if __name__ == '__main__':add(2, 3)

index.py

import custom_module
custom_module.add(1,2)

all

只有 __all__中有的函数才能在 from custom_module import * 引入方式中使用

__all__ = ['subtract']def add(num1, num2):print(num1 + num2)def subtract(num1, num2):print(num1 - num2)
from custom_module import *
subtract(1,2)
add(1,2) # "add" is not defined

自定义包

必须有 init.py 可以为空文件
custom_package/init.py

__all__ = ['module']

custom_package/module.py

def add(num1, num2):print(num1 + num2)

index.py

import custom_package.module
custom_package.module.add(1,3)from custom_package.module import add
add(2,4)

all

from custom_package import *
module.add(2,4)

使用第三方包 pip

下载
pip install 包名
使用镜像加速
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple 包名

json

import json把 python 数据转化 json 数据
json.dumps(user)把 json 数据转化 python 数据
json.loads(user)

类的成员和方法

class Student:name = None# 此时方法中 self 必填def say_hi(self):print(f"{self.name}")stu = Student()
stu.name = 'xr'
stu.say_hi()

构造方法

class Student:# 此处变量可以省略name = Nonedef __init__(self, name):self.name = nameprint('__init__')# 实例化时构造方法就会执行
stu = Student('xr')

封装 私有成员和方法 在方法前加上 __

只能在类内中使用

class Student:__name = Nonedef __say_hi(self):print("__say_hi")stu = Student()
stu.__say_hi() # 'Student' object has no attribute '__say_hi'

继承

单继承

class Person:def print_info(self):print('person')class Student(Person):def print(self):print('student')stu = Student()
stu.print()

多继承

class Person:def print_info(self):print('person')class Teacher:def print_info(self):print('Teacher')class Student(Teacher, Person):# pass 解决不写内容报错passstu = Student()
stu.print_info() # Teacher

子类中调用父类中的方法


class Person:def print_info(self):print('person')class Student(Person):def print(self):# 方式1Person.print_info(self)# 方式2 此时不需要传 selfsuper().print_info()stu = Student()
stu.print()

类型注解

变量类型注解

# 类对象注解
class Student:passstu: Student = Student()
# 基础容器类型注解
list: list = [1, 2]
tuple: tuple = (1, '2')
dict: dict = {"name": "xr"}
# 容器类型详细注解
list: list[int] = [1, 2]
tuple: tuple[int,str] = (1, '2')
dict: dict[str,str] = {"name": "xr"}
# 在注释中进行类型注解
num = 10 # type: int

函数和方法类型注解

# 形参就行类型注解
def add(x: int, y: int):x+y# 函数返回值就行注解
def add(x: int, y: int) -> int:return x+y

混合类型注解
Union

from typing import Unionlist: list[Union[str, int]] = [1, 'a']
dict: dict[str, Union[str, int]] = {"name": "xr","age": 18
}

多态

闭包

此时 num1 在 inner 中不能修改

def outer(num1):def inner(num2):print(f"{num1} = {num2}")return innerfn = outer(1)
fn(2) # 1 = 2

使用 nonlocal 修饰符

def outer(num1):def inner(num2):nonlocal num1num1 += num2print(f"{num1}")return innerfn = outer(1)
fn(2) # 3

装饰器

写法1

import time定义一个 sleep 函数,不改变函数情况下增加功能
def sleep():print('睡眠中...')time.sleep(1)def outer(cb):def inner():print('新增逻辑1')cb()print('新增逻辑2')return innerfn = outer(sleep)
fn()

使用语法糖

import timedef outer(cb):def inner():print('新增逻辑1')cb()print('新增逻辑2')return inner@outer
def sleep():print('睡眠中...')time.sleep(1)sleep()

设计模式

单例模式
app.py

class Utils:passutils = Utils()

index.py

from app import Utilsu1 = Utils
u2 = Utils
print(id(u1)) #1381794304896
print(id(u2)) # 1381794304896

工厂模式

class Person:passclass Student(Person):passclass PersonFactory:def get_person(self,type):if type == 's':return Studentp = PersonFactory()
s = p('s')