a = 12 print(f"hello{a}") print("hello%d" %a) # 作用相同
2.赋值随机数
1 2 3 4
import random a = random.randint(1,100) # 包含1~100间的整数 b = random.unitform(1,100) # 包含1~100间的小数 c = random.random() # 0~1的小数
3.布尔运算 and or not (与或非)
1 2 3 4
a = False b = not a c = a or b d = a and c
4.字符串拼接复制
字符串拼接用“+”
字符串复制用“*”
条件和循环
1.while
循环变量要增加避免死循环
(1)执行规则
1 2 3 4 5
a = 0 while a<10: # 若符合条件则循环执行 a += 1 print(a) print("end") # 若不符合条件则执行
(2)break语句
1 2 3 4 5
while a<10: a += 1 print(a) if a == 5: break# 中途跳出循环不再执行
(3)continue语句
1 2 3 4 5 6 7 8 9
a = 0 while a <100: while a <10: a += 1 print(a) if a ==5: continue# 跳过当前循环的一项,继续执行上一级循环 print("e") print("end")
(4)while True:死循环
2.for
1.循环变量,遍历列表
1 2 3
for i inrange(10): #0~9的列表 print("我错了") print("下次还敢")
等同于:for i in[0,1,2,3,4,5,6,7,8,9]
左闭右开
a = range(5) #[0,5)
a = range(-1,5) # [-1,5)
2.自定义循环
“s”可为列表,字符串,集合,元组
1 2 3
s = [1,3,5,7,8] for i in s: print(i)
1 2 3
s = "abcde" for i in s : print(s)
3.else 与 break
一般循环结束跳转else,break结束则不再执行else—while语句同样适用
1 2 3 4 5 6
for i inrange(10): print(i) if i == 5: break else: print("循环正常结束")
字符串
1.切片
1 2 3 4 5 6 7 8
a = "my name is xxx" a = a[1:5] # 下标1-5 左闭右开,不包括5 0[1234]5 a = a[:5] # 从开始到4 a = a[1:] # 从1开始到最后 a = a[:] # 全部 a = a[1:5:2] # 从1-4,步长为2 a = a[::-1] # 把字符串反过来 a = [-5:-1] # 倒数-5~-1 不包括-1
2.替换
a = a.replace("xxx","pig")
3.分割
arr = a.split"" 得到列表
4.拼接
string = "-".join(arr) 将列表拼成字符串,本代码以”-“拼接
5.指针
1 2 3
string = "app" s = string[0] # s = a
1 2 3
s = [1,2,3,4] s = s[0] # s = 1
列表
1.指针规则
1 2 3
arry = [[1,2,3],[4,5,6],[7,8,9]] a = arry[1] # a = [4,5,6] b = arry[1][2] # b = 6
2.遍历大列表
1 2 3 4 5 6 7 8 9
arry = [ [[1,2,3],[4,5,6],[7,8,9]] [[1,2,3],[4,5,6],[7,8,9]] [[1,2,3],[4,5,6],[7,8,9]] ] for a in arry: for b in a: for c in b: print(c)
3.判断是否在(不在)列表中
1 2 3
a = [1,3,6] if1 (not) in a: print("…")
4.在列表中添加元素
a.append("abc") 在列表末尾添加“abc”
a.insert(1,"t") 在下标为1的元素前添加“t”
5.删除
1 2 3 4 5 6
b = 12 a = [1,False,"happy",b,[1,2,3]] a.pop(0) # 用下标 a.remobe("happy") # 用元素 a.clear() # 清空列表 del a # 删除a
6.赋值
1 2 3
b = 12 a = [1,False,"happy",b,[1,2,3]] a[0] = 123# 给下标为[0]的元素赋值
1 2
string = "avc" string[0] = "b"
1 2
b = a # 这样赋值后,b随着a的改变而改变 b = a.copy() # 复制后可a变b不变
7.排序
1 2 3
a = [4,2,1,3] a.sort() # 直接修改 a = sorted(a) # 有返回值
元组,集合,字典
1.元组不可被修改,可以被访问
2.遍历访问
1 2 3 4 5 6 7
a = "12345" b = [1,2,3,"t",4,5] c = (1,2,"22") for i in b: print(i) for i inrange(len(c)): print(c[i])
Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.