链式赋值code
多个变量赋同一个值:orm
通常方法:索引
a = 10 b = 10 c = 10 print(f'a:{a}, b:{b}, c:{c}')
链式赋值方法:字符串
a = b = c = 10 print(f'a:{a}, b:{b}, c:{c}')
两种方法的结果是同样的:input
a:10, b:10, c:10, d:10
交叉赋值string
互换两个变量的值:it
通常方法:form
x = 100 y = 200 z = x x = y y = z print(f'x:{x}') print(f'y:{y}')
交叉赋值方法:class
x, y = y, x print(f'x:{x}') print(f'y:{y}')
两种方法的结果是同样的:
x:200 y:100
以上两种方法不多会用到,仅做了解。
列表:
什么是列表
列(序列)表(表格),一列(存储多个元素)表格,描述一我的的爱好
做用
存储多个(任意数据类型)元素
定义方式:[]内用逗号隔开多个元素(任意数据类型): lt = [1,2,'str'…]
使用方法:索引
lt = [1, 2, 3, 'str'] print(lt[1]) # 打印lt列表内的第二个元素
结果:
2 Process finished with exit code 0
字典:
做用:存储多个具备描述信息的任意数据类型的元素
定义方式:{}内用逗号隔开多个键(描述,用字符串):值(具体的值,能够为任意数据类型)对
使用方法:按key取值
dic={'a':1,'b':2} print(dic['a']) # 取出字典内,键为'a'的值
结果:
1 Process finished with exit code 0
布尔类型:
做用:用于判断条件结果,为真则值为 True
,为假则值为 False
定义方式:True、False一般状况不会直接引用,须要使用逻辑运算获得结果。
使用方法:全部数据类型都自带布尔值,除了 0/None/空(空字符/空列表/空字典)/False
以外全部数据类型自带布尔值为 True
。
print(bool(0)) print(bool('nick')) print(bool(1 > 2)) print(bool(1 == 1))
结果:
True False False False False False Process finished with exit code 0
解(解开)压缩(容器类数据类型):只针对2-3个元素容器类型的解压。
一次性取出列表里全部的值:
通常方法:索引取值:
实现代码:
lt = [1, 2, 3, 4, 5] print(lt[0]) print(lt[1]) print(lt[2]) print(lt[3]) print(lt[4])
结果:
1 2 3 4 5 Process finished with exit code 0
解压缩取值方法:
lt = [1, 2, 3, 4, 5] s1, s2, s3, s4, s5 = lt # 列表内有几个值,就必须有几个变量 print(s1, s2, s3, s4, s5)
结果:
1 2 3 4 5 Process finished with exit code 0
当列表内的值不是咱们须要的,用下划线占位
lt = [1, 2, 3, 4, 5] s1, _, _, s4, _ = lt # 下划线占掉不须要的值的位置,表示咱们不须要这个值 print(s1, s4, )
结果:
1 4 Process finished with exit code 0
*_
lt = [1, 2, 3, 4, 5] s1, *_, s5 = lt print(s1, s5) print(_)
结果:
1 5 [2, 3, 4] Process finished with exit code 0
方法:使用 input()
实现:
input()
的做用:
接收用户的输入传给变量,而且接受内容永远是字符串类型
使用 input()
时,应该写清楚但愿用户输入什么内容
例:
user_input = input('请输入身高:') print('你的身高是:', user_input)
结果:
请输入身高:185 # 程序运行后先显示‘请输入身高:’,等待用户输入后,按回车键 你的身高是: 185 # 打印出用户输入的身高 Process finished with exit code 0
python2和python3中input()的区别
f-string 格式化---(经常使用)
name='tom' print(f'hello,{name}.') # f使字符串内的{}变的有意义,里面的内容变成了变量名
结果:
hello,tom. Process finished with exit code 0
占位符:%s
(针对全部数据类型)、%d
(仅仅针对数字类型)
name='tom' print('hello,%s.' % (name))
结果:
hello,tom. Process finished with exit code 0
format格式化
name='tom' print('hello,{}'.format(name))
结果:
hello,tom. Process finished with exit code 0