Python档案袋(变量与流程控制)

时间:2021-12-23 06:21:06

变量与运算

得到数据类型:

ii=100
print(type(ii)) #输出:<class 'int'>

强制转换:

ii=100
iix=str(ii) #可为int str float
print(type(iix)) #输出:<class 'str'>

删除变量:

del 变量名

整数:int,python3已经无长整型之说

bool类型:其中None可以等价于False

相关方法

 print(bool(-1)) #判断值是真是假,输出:True
print(type("")) #类型,输出:<class 'str'> print(bin(3)) #十进制转换为二进制,输出:0b11
print(hex(255)) #将十进制转换为十六进制,输出:0xff
print(hex(0b11)) #进二进制转换为十六进制,输出:0x3
print(oct(7)) #将十进制转换为八进制,输出:0o7 print(chr(99)) #输出对应的ASCII字符,输出:c
print(ord('c')) #输出对应ASCII数字,输出:99 print(abs(-100)) #绝对值,输出:100
print(divmod(10,3)) #相除,返回商和余数,输出:(3, 1)
print(max(10,6)) #比较大小,输出:10
print(min(10,6))#比较大小,输出6
print(pow(2,3)) #2的3次方,等同于2**3,输出:8
print(round(1.335,2)) #保留小数点后几位,测试为五舍六入,输出:1.33

变量的作用域: 以函数为区域单位,一个函数确定一个作用区域

全局变量:在首部定义,只要在调用普通函数或者类方法前定义则可以直接使用,这样只可以实现方法里的使用,不能修改(包括数字、字符串,如果是字典、集合、列表则可以直接更改),如果想修改则需在函数内最开始处加入【global 变量名】

整数实例:

 #必须使用global
intx=12
def funx1():
global intx
intx+=100
print(intx)#输出:112 funx1()
print(intx) #输出:112

列表实例:

 #不用使用global
listx=[11,22,33,44,99]
def funx1():
listx[2]="xxxxxxx"
print(listx)#输出:[11, 22, 'xxxxxxx', 44, 99] funx1()
print(listx) #输出:[11, 22, 'xxxxxxx', 44, 99]

流程控制

三元运算:

#res等于100的条件是10大于9,否则res值为5
res=100 if 10<9 else 5
print(res) #输出:5

断言:

断言句可以实现条件判断,成立则继续向下执行,条件不成立则报异常并退出程序,断言异此(AssertionError)可以被捕获

a=1
assert a==3 #断言a的值为3
print("已经确定a的值为1") #此程序不输出,直接报错

判断:

if…elif…else使用:

条件符号有【==】、【!=】、【and】、【or】、【not】、【is】、【is not】

 v1=""
v2=""
v3=""
if v1 == v2 and v2 == v3: #与判断
print("相同")
elif v1==v3:
print("相同2")
else:
print("不同")

while…else使用:

 while False: #True:
#continue 跳出本次循环
#break 跳出整个循环
print("循环中.......")
else:
print("条件失败执行...")
print("一定执行...")

for循环使用:

 #for i in range(10):#区间为[0,10)
#for i in range(100,110): #区间为[100,110) ,递增
#for i in range(10, 1,-1):#区间为[10,1) ,递减
for i in range(2,10,2): #步长为2进行循环,输出:2 4 6 8
if i==4:
#continue #跳出本次循环
#break #跳出整个循环
pass #占位,无意义
print(i)