python 基础语法记录

Python

查看版本

py --version 
Python 3.11.1

django-admin --version
4.2.1

注释

  • 单行注释
    #

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

变量的定义

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 = 12

if 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
    # age
    print(key)

for value in user.values():
    # xr
    # 20
    print(value)

for key,value in user.items():
    # name xr
    # age 20
    print(key,value)


for item in user.items():
    # ('name', 'xr')
    # ('age', 20)
    print(item)

函数

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

函数返回值

def sum(a,b):
   return a+b

res = 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+y

test(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 + y
    print(f'x+y: {result}' )
    return result

add(1,2)

全局变量局部变量

num = 100
print(num) # 100

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

init()
print(num) # 100

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

num = 100
print(num) # 100

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

init()
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 = None

    def __init__(self, name):
        self.name = name
        print('__init__')

# 实例化时构造方法就会执行
stu = Student('xr')

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

只能在类内中使用

class Student:
    __name = None

    def __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 解决不写内容报错
    pass

stu = Student()
stu.print_info() # Teacher

子类中调用父类中的方法


class Person:
    def print_info(self):
        print('person')

class Student(Person):
    def print(self):
        # 方式1
        Person.print_info(self)
        # 方式2 此时不需要传 self
        super().print_info()

stu = Student()
stu.print()

类型注解

变量类型注解

# 类对象注解
class Student:
    pass

stu: 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 Union

list: 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 inner

fn = outer(1)
fn(2) # 1 = 2

使用 nonlocal 修饰符

def outer(num1):

    def inner(num2):
        nonlocal num1
        num1 += num2
        print(f"{num1}")

    return inner


fn = 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 inner

fn = outer(sleep)
fn()

使用语法糖

import time

def outer(cb):
    def inner():
        print('新增逻辑1')
        cb()
        print('新增逻辑2')
    return inner

@outer
def sleep():
    print('睡眠中...')
    time.sleep(1)

sleep()

设计模式

单例模式
app.py

class Utils:
    pass

utils = Utils()

index.py

from app import Utils

u1 = Utils
u2 = Utils
print(id(u1)) #1381794304896
print(id(u2)) # 1381794304896

工厂模式

class Person:
    pass

class Student(Person):
    pass

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

p = PersonFactory()
s = p('s')

多线程

import threading
创建线程
thread_obj = threading.Thread()
# 启动线程
thread_obj.start()

示例

import threading
import time


def sing():
    while True:
        print('唱歌....')
        time.sleep(1)


def dance(msg):
    while True:
        print(msg)
        time.sleep(1)


if __name__ == '__main__':

    sing_thread = threading.Thread(target=sing)
    # 元组形式传参
    dance_thread = threading.Thread(target=dance,args=('跳舞...',))
    # 字典形式传参
    # dance_thread = threading.Thread(target=dance, kwargs={"msg": "字典形式"})

    sing_thread.start()
    dance_thread.start()

socket

服务端代码

import socket
# 创建 socket 对象
socket_server = socket.socket()

# 绑定 ip 地址和端口
socket_server.bind(("localhost", 8888))


print('等待客户端链接')
# 监听端口
# 接收的连接数量
socket_server.listen(2)
# 等待客户端链接
# accept()方法是阻塞的方法,等待客户端的链接,如果没有链接,就卡在这一行不继续执行
# result:tuple  = socket_server.accept()
# conn = result[0] # 客户端和服务端的连接对象
# address = result[1] # 客户端的地址信息

conn, address = socket_server.accept()
print(f"接收到了客户端连接{conn}{address}")
while True:

    # 接收客户端信息
    # recv 接收的参数是缓冲区大小,一般 1024 即可
    # recv方法的返回值是一个字节数组也就是 bytes 对象,通过 decode 方法转换为字符串对象
    data = conn.recv(1024).decode('utf-8')
    print(f"客户端发送的消息:{data}")

    # 发送回复消息
    # encode 可以将字符串编码为字节数组对象
    msg = input("请输入发送给客户端的信息:")
    if msg == "exit":
        break
    conn.send(msg.encode("utf-8"))

# 关闭链接
conn.close()
socket_server.close()


客户端代码

import socket

socket_client = socket.socket()

socket_client.connect(('localhost', 8888))

while True:
    msg = input("请输入发送给服务端的信息:")
    socket_client.send(msg.encode("utf-8"))
    recv_data = socket_client.recv(1024)
    print(f"服务端回复的消息:{recv_data.decode('utf-8')}")

socket_client.close()
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值