Python基础
Python 常见变量#
Number#
支持 int float complex bool
String#
描述文本
List#
有序的记录一堆数据
Tuple#
有序的不可变的 python.assets 数据
Dictionary#
无序的 key-value 型
Set#
无序不重复的集合
注释#
单行注释#
# 注释
#我是注释
多行注释#
"""
我是多行注释
"""
强制类型转化#
int() float() str()
字符串#
字符串定义的方法#
text1 = "i'am string "
text2 = '我是字符串'
text3 = """我是注释,也是字符串"""
算数运算符#
字符串拼接#
k = "为若柳絮因风起"
print("s"+k)
# 编译结果
# s为若柳絮因风起
字符串格式化#
传统格式化#
print("HELLO IAM",name,"今年",age)
控制格式化#
k = "为若柳絮因风起"
m = "撒盐空中差可拟 %s"%k
print(m)
# 撒盐空中差可拟 为若柳絮因风起
# %s %d %f
# %为占位提示
age = 23
sub = "python.assets"
message = "我今年%d了,我正在学%s"%(age,sub)
print(message)
#我今年23了,我正在学python.assets
快速格式化#
name = "alice"
age = 24
print(f"i am {name:.2f} age is {age}")
pi = 3.1415926
print("pi is %0.2f"%pi)
input()#
print()#
print 表达式技巧#
print("1 * 1 = %d"%(1*1))
print(f"1 * 1 = {1*1}")
print 不换行技巧#
print("helloxixi",end='')
print("hello one line")
#helloxixihello one line
print 对齐多行技巧#
print("hello\tnihao")
print("i am\thhh")
If 语句#
x = 2
y = 3
if x > y:
print("x is big")
else:
print("y is big than x")
IF 多重语句#
x = 2
y = 3
if x > y:
print("x is big")
elif x == y:
print("x is same y")
else:
print("y is big than x")
While#
i = 0
while i < 10:
print("Hello Word")
i+=1
FOR 循环遍历#
name = "wangbo"
for x in name:
#将name的内容,挨个取出挨个分析
print(x)
"""
w
a
n
g
b
o
"""
range 语句#
for x in range(10):
print(x)
"""
0
1
2
3
4
5
6
7
8
9
"""
讨论 for 的临时变量#
for i in range(5):
print(i)
print(i)
# i为临时变量 可以看到为4 但是实际上不可以 最好提前定义i
九九乘法表#
for i in range(1,10):
for j in range(1,i+1):
print(f"{j}*{i}={j*i}\t",end='')
print()
函数#
函数定义#
def hh():
print("欢迎来到def定义函数")
hh()
#欢迎来到def定义函数
函数传参数#
def hh(a,b):
result = a+b
print(f"{a}+{b}={result}")
hh(2,3)
函数返回值#
def hh(a,b):
result = a+b
return result #遇到return就出栈了
r = hh(2,3)
print(r)
#
函数多返回值#
def test():
return 1,2
x, y = test()
print(x)
print(y)
#1
#2
函数传参#
def user_info(name,age,gender):
print(f"姓名:{name},年龄是{age},性别是:{gender}")
#默认
user_info("小明",20,'男')
#关键字参数
user_info(name="小王",age = 11, gender="男")
user_info(age = 12,name="效力", gender="男")
user_info("小赵",gender="女",age=19)
函数缺省传递#
# 缺省传参必须放在最后
def user_info(name,age,gender = '男'):
print(f"姓名:{name},年龄是{age},性别是:{gender}")
#默认
user_info("小明",20)
user_info("小明",20,"女")
"""
姓名:小明,年龄是20,性别是:男
姓名:小明,年龄是20,性别是:女
"""
不定长传参#
利用元组传不定长#
def user_info(*args): #规范写法
print(args)
user_info('tom')
user_info("tom",18)
利用字典传不定长#
def user_info(**args):
print(args)
user_info(name = "tom",age = 19)
#{'name': 'tom', 'age': 19}
函数作为传参值#
def test(compute):
result = compute(1,2)
print(f"计算结果:{result}")
def compute(x,y):
return x + y
test(compute)
Lambda 匿名函数#
def test(compute):
result = compute(1,2)
print(f"计算结果:{result}")
#lambda 只能写一行且只能用一次
test(lambda x,y:x + y)
None#
函数的说明文档#
对函数中的变量或者函数的返回结果来进行说明
def check(age):
_"""_
_ :param age: 形参的说明_
_ :return: 返回值的说明_
_ """_
_ _if age > 19:
return "success"
else:
return None
函数中使用全局变量#
因为函数中的变量都是局部变量 用 global 来在函数内定义为全局变量
数据容器#
List 列表#
列表切片#
#列表名[start:stop:step]
# 定义一个列表
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 使用切片操作获取列表中的前三个元素
result = numbers[0:3]
# 输出切片结果
print(result)
#[1, 2, 3]
# 定义一个列表
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 使用切片操作获取列表中的偶数位置的元素
result = numbers[::-1]
# 输出切片结果
print(result)
#[1, 3, 5, 7, 9]
#步数切片
# 定义一个列表
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 使用切片操作逆序获取列表中的元素
result = numbers[::-1]
# 输出切片结果
print(result)
#[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
#
列表定义#
#列表定义
namelist=["apple","banana","orange"]
print(namelist)
print(type(namelist))
空列表#
#列表定义
namelist=["apple","banana","orange"]
print(namelist)
print(type(namelist))
嵌套列表#
#嵌套列表
namelist=[[1,2,3],"banana","orange"]
print(namelist)
列表的下标索引#
namelist=[[1,2,3],"banana","orange"]
print(namelist[0][1])
#输出为2
print(namelist[-1])
#输出为orange
列表的方法(class 类的成员)#
index()查找下标
namelist=[[1,2,3],"banana","orange"]
index = namelist.index("orange")
print(index)
修改特定下标的索引
#修改列表下标
namelist=[[1,2,3],"banana","orange"]
namelist[1] = "photo"
print(namelist[1])
insert 插入元素
#插入列表元素
namelist=[[1,2,3],"banana","orange"]
namelist.insert(1,"photo")
print(namelist)
append 追加元素
#追加列表元素
namelist=[[1,2,3],"banana","orange"]
namelist.append("niubi")
print(namelist)
extend 追加容器
#追加容器
namelist=[[1,2,3],"banana","orange"]
namelist2 = [1,2,4,5]
namelist.extend(namelist2)
print(namelist)
*del 删除 非列表方法
删除元素
namelist=[[1,2,3],"banana","orange"]
del namelist[1]
print(namelist)
#[[1, 2, 3], 'orange']
pop 删除
元组#
元组的定义#
# 定义元组
r = (1,2,2,3,3)、
#定义空元组
r = tuple()
r = ()
# 元组不可修改
元组单个元素定义#
t =("hello")
print(f"t type is{type(t)}")
t =("hello",)
print(f"t type is{type(t)}")
元组取内容#
t =("hello","kakao","zeus")
print(f"the first is {t[0]}")
元组的操作#
index
count
len
t =("hello","kakao","zeus")
index = t.index("zeus")
c = t.count("zeus")
c1 = len(t)
print(index)
print(f"c1 len is {c1}")
循环相同#
元组内的嵌套的列表可以修改#
t =("hello","kakao","zeus",[1,2,3])
t[3][2] = 7
print(t)
#('hello', 'kakao', 'zeus', [1, 2, 7])
字符串#
字符串切片#
提取字符串
text = "Hello, World!"
substring = text[7:12]
print(substring) # 输出 "World"
#缺省切片
text = "Python Programming"
first_three = text[:3] # 等同于 text[0:3]
last_four = text[-4:] # 等同于 text[-4:len(text)]
print(first_three) # 输出 "Pyt"
print(last_four) # 输出 "ming"
#步长切片
text = "Python Programming"
even_chars = text[::2]
print(even_chars) # 输出 "Pto rgamn"
字符串的下标索引#
s = "hello"
first = s[0]
last = s[-1]
print(f"fist is {first},last is {last}")
#fist is h,last is o
字串的操作#
index
s = "hello"
i = s.index("l")
print(f"fist is {i}")
#### return 2
Replace
s = "hello niko"
new_s = s.replace("niko","zeus")
#原来的字符串没有改变
print(s)
#新的字符串产生
print(new_s)
"""
hello niko
hello zeus
"""
split
s = "hello niko"
new_s = s.split(" ") ###### 用空格进行分割
#原来的字符串没有改变
print(s)
#新的字符串产生
print(new_s)
"""
hello niko
['hello', 'niko']
"""
Strip
s = "hello nikoeh"
new_s = s.strip("he") #缺省只删除前后空格或者换行符 满足任意h or e 都是删除
#新的字符串产生
print(new_s)
"""
llo niko
"""
Count
s = "hello nikoeh"
c = s.count("o")
print(f"o is comment {c}")
len
str1 = "hello"
long = len(str1)
print(long)
#输出是5
序列#
序列的切片不会影响序列的本身,而是会得到一个新的序列
mylist = [0,1,2,3,4,5,6]
str = "0123456"
result = mylist[1:4]#步长省略为1
print(f"result is {result}")
#result is [1, 2, 3]
result1 = mylist[::2]
print(f"result1 is {result1}")
#result2 is [0, 2, 4, 6]
result2 = mylist[::-1]
print(f"result2 is {result2}")
#result2 is [6, 5, 4, 3, 2, 1, 0]
#
集合#
# set定义
myset = {1,1,1,1,12,2,3,5,}
print(f"myset is{type(myset)}")
print(myset)
#set 空定义
myset2 = set()
print(f"myset is{type(myset2)}")
#不可这种空定义
myset3 = {}
print(f"myset is{type(myset3)}")
#myset is<class 'dict'>
字典#
#定义字典
my_dict={"k1":99,"k2":100,"k3":44}
#定义空字典
my_dict2 = {}
my_dict3 =dict()
基于 key 获得 value#
#定义字典
my_dict={"k1":99,"k2":100,"k3":44}
score = my_dict["k1"]
print(score)
#99
基于表格保存字典#
dict = {
"王力宏":{
"语文":99,
"数学":66,
"英文":33
},
"周杰伦":{
"语文":99,
"数学":66,
"英文":33
},
"林俊杰":{
"语文":99,
"数学":66,
"英文":33
}
}
新增元素#
dict1 = {"k1":99}
#更新
dict1["k1"] = 100
#新增
dict1["k2"] = 90
print(dict1)
删除元素#
pop()中通过删除 key 返回 value 值
dict1 = {"k1":9,"WE":99}
score = dict1.pop("k1")
print(dict1)
#{'WE': 99}
# 9
清空元素#
dict1 = {"k1":9,"WE":99}
dict1.clear()
print(dict1)
获得全部 key#
dict1 = {"k1":9,"WE":99}
key = dict1.keys()
print(key)
#dict_keys(['k1', 'WE'])
字典遍历
For
方式 1
dict1 = {"k1":9,"WE":99}
keys = dict1.keys()
for key in keys:
print(f"字典的key是{key}")
print(f"字典的value是{dict1[key]}")
方式 2
dict1 = {"k1":9,"WE":99}
for key in dict1:
#key 每次都存储字典的key值
print(f"字典的key是{key}")
print(f"字典的value是{dict1[key]}")
统计字典的元素数量#
dict1 = {"k1":9,"WE":99}
l = len(dict1)
print(l)
#
容器通用元素#
类型转换#
my_list = [1,2,3,4,5]
my_tuple = (1,2,3,4,5)
my_str = "abcdef"
my_set = {1,2,3,4,5}
my_dict = {"key1":1,"key2":2,"ke3":3,"key4":4}
print(f"列表转列表的结果是{list(my_list)}")
print(f"列表转列表的结果是{list(my_tuple)}")
print(f"列表转列表的结果是{list(my_str)}")
print(f"列表转列表的结果是{list(my_set)}")
print(f"列表转列表的结果是{list(my_dict)}")
数据容器排序#
文件#
打开文件#
f = open("py.txt","r",encoding="UTF-8")
读取文件的方法#
read()#
#读取文件
#10表示只读10个字节 缺省读全部
f1 = f.read(10)
print(f"{f1}")
#从上次读到的位置继续读取->关于指针的问题
f2 = f.read()
print(f"{f2}")
readlines()#
f = open("py.txt","r",encoding="UTF-8")
lines = f.readlines() #读取文件的全部行 封装到列表中
readline#
f = open("py.txt","r",encoding="UTF-8")
lines = f.readline() #读取一行
利用 for 循环读取文件#
f = open("py.txt","r",encoding="UTF-8")
for line in f:
#每个line存入一行数据
print(line)
With for#
with open("py.txt","r",encoding="UTF-8") as f:
for line in f:
print(f"{line}")
文件写入#
f = open("py.txt","w",encoding="UTF-8") # w会覆盖写
f.write("hello") #内容写入到内存中
文件内容刷新#
f.flush() #将内存中积攒的内容写入硬盘中
f.close() #close也内置flush方法
文件关闭#
f = open("py.txt","r",encoding="UTF-8")
f.close()
捕获异常#
基本异常#
try:
f = open("1.txt","r",encoding = "utf-8")
except:
print("出现异常了,因为文件不存在,我讲open模式改为w模式")
f = open("1.txt","w",encoding = "utf-8")
捕捉指定异常#
try:
print(name)
except NameError as e: # e为存储异常内容的变量
print("出现了变量未定义")
print(e)
捕获多个异常#
try:
1/0
print(name)
except(NameError,ZeroDivisionError) as e:
print("出现了变量未定义 或者 除以0的异常错误")
捕获全部异常#
try:
1/0
print(name)
except Exception as e:
print("出现了异常")
Python 模块#
定义#
python.assets 模块就是一个 py 文件
基本使用#
import time #导入time模块
print("你好")
time.sleep() #程序睡眠多久
print("你好")
From#
#导入时间模块中的sleep方法
from time import sleep
print("你好")
sleep()
print("你好")
#导入时间模块中的所有方法
from time import *
print("你好")
sleep() #使用时候可以抛弃#
print("你好")
Python 包#
导入包#
import my_package.模板名
my_package.模板名.函数()
from my_package import 模块名
模块名.函数()
from my_package.模块名 import 函数
函数()
通过 All 文件控制*#
all 文件书写#
__all__ = ["模块名"]
引入书写#
from my_package import *
模块名.函数名()
安装第三方包#
pip install 包
pip install -i 网址 包名称
Python 类的行为和对象#
类的对象--数据#
class stu:
name = None
age = None
stu1 = stu()
stu1.name = "王"
stu1.age = 20
print(stu1.name)
类的行为--方法#
class stu:
name = None
age = None
def sayname(self):
print(f"我的名字是{self.name}")
def say2(self,msg):
print(f"我的名字是{self.name},{msg}")
def ring(self):
import winsound
winsound.Beep(2000,3000)
#self在函数内部必须书写 用于自己调用自己的成员名
#self在当方法时候不需要出现 忽略即可
stu1 = stu()
stu1.name = "王"
stu1.age = 20
stu1.sayname()
stu1.say2("哎哟不错哦")
stu1.ring()
构造方法#
class stu:
#构造方法自动执行-->>就是直接传参
def __init__(self,name,age):
self.name = name
self.age = age
print("1")
stu1 = stu("王博聪",18)
print(stu1.name)
魔术方法#
class stu:
#构造方法自动执行
def __init__(self,name,age):
self.name = name
self.age = age
print("1")
def __str__(self):
return f"name:{self.name} age:{self.age}"
def __lt__(self, other):
return self.age < other.age
def __le__(self, other):
return self.age <= other.age
def __eq__(self, other):
return self.age == other.age
stu1 = stu("王博聪",18)
stu2 = stu("王",31)
print(stu1)
print(stu1 < stu2)
print(stu1 <= stu2)
print(stu1 == stu2)
封装#
私有成员变量与方法#
class phone:
__name = "型号已经启动"
__volatage = None
def __keep_core(self):
print("cpu单核运行")
sanxign = phone()
继承#
单继承#
class phone():
IEM = None
def show_4g(self):
print("开启4g模式")
#单继承
class phone22(phone):
def show_5g(self):
print("今年有5g模式奥")
sanxing = phone22()
sanxing.IEM = "101010011"
print(sanxing.IEM)
sanxing.show_5g()
多继承#
class phone():
IEM = None
def show_4g(self):
print("开启4g模式")
class nfc:
nfc_type = "第五代"
class galaxy(phone,nfc):
type = "w2023心系天下"
wang = galaxy()
galaxy.IEM = "c113131"
print(galaxy.IEM)
print(galaxy.nfc_type)
复写#
复写属性
class phone():
IEM = "17641207780"
class nfc:
nfc_type = "第五代"
IEM = "1584222300"
class galaxy(phone,nfc):
IEM = "复写父类成员"
type = "w2023心系天下"
wang = galaxy()
print(galaxy.IEM)
复写
直接覆盖复写
class phone():
IEM = "17641207780"
def show_4g(self):
print("开启4g模式")
class nfc:
nfc_type = "第五代"
IEM = "1584222300"
class galaxy(phone,nfc):
def show_4g(self):
print("开启4g模式")
print("开启省电模式")
IEM = "复写父类成员"
type = "w2023心系天下"
wang = galaxy()
wang.show_4g()
调用父类成员复写
class phone:
IEM = "17641207780"
pro = "Sunsang"
def show_4g(self):
print("开启4g模式")
class nfc:
nfc_type = "第五代"
IEM = "1584222300"
class galaxy(phone):
pro = "心系天下"
def show_4g(self):
#方法一
print(super().pro)
super().show_4g()
#方法二
print(super().pro)
super().show_4g()
print("开启省电模式")
wang = galaxy()
wang.show_4g()
类型注释#
基础数据类型注释#
var = 10
var: int = 10
var = "kk1234"
var: str = "kk1234"
类对象类型注释#
class student:
pass
stu = student()
stu:student = student()
基础容器类型注释#
基本注释
lst:list = [1,2,3]
tup:tuple = (1,2,3)
my_set:set = {1,2,3}
my_dict:dict = {"kk":666}
详细注释【3.9 版本以上】
lst:list[int] = [1,2,3]
tup:tuple[int,str] = (1,"ithe") #需要标注每个元素
my_set:set[int] = {1,2,3}
my_dict:dict[str,int] = {"kk":666}
注释写法#
import json
import random
var1 = random.randint(1,10) #type: int
var2 = json.loads({"name","zhangsan"}) #type: dict[str,str]
def func():
return 1
var_3 = func() #type: int
函数形参注释#
def func(x:int,y:int):
return x + y
func() #按ctrl+p查看参数类型
函数返回值注释#
def func(x:int,y:int)->int:
return x + y
func() #按ctrl+p查看参数类型
Union 类型#
基本类型
from typing import Union
my_set:set[int,str] = {1,2,3,"123"}
my_dict:dict[str,Union[int,str]] = {"kk":"123","age":31}
函数类型
from typing import Union
def func(data:Union[str,int])-> Union[int,str]:
pass
func()
多态#
抽象类#
#定义一个标准
class Animal:
#抽象的方法
def speak(self):
pass
#用子类来实现这种方法
class dog(Animal):
def speak(self):
print("汪汪汪")
class cat(Animal):
def speak(self):
print("喵喵喵")
def make_noise(animal:Animal):
animal.speak()
dog = dog()
cat = cat()
make_noise(dog)
make_noise(cat)
生成式#
列表生成式#
# 列表生成式示例一:生成1到10的平方列表
squares = [x ** 2 for x in range(1, 11)]
print(squares)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~