Day 04 与用户交互、格式化输出及基本运算符
Day 04的内容总结
-
与用户交互
-
格式化输出
-
基本运算符
与用户交互
用户交互就是人往计算机中input/输入数据,计算机print/输出结果
输入 input
>>>res = input('please input your uername>>>') >>>print(res,type(res)) please input your uername>>>koala koala <class 'str'>注意点:
python3与python2的区别:
python3中input存储的内容默认存成字符串str类型
python2中,input需要用户人为的指定输入的数据类型,不方便用户
>>> res = input('please input your uername>>>') please input your uername>>>koala Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> NameError: name 'koala' is not defined如果想要达到python3的效果,需要使用raw_input
>>> res = raw_input('please input your uername>>>') please input your uername>>>koala >>> print(res,type(res)) ('koala', <type 'str'>)python2中的raw_input等价于python3中的input
输出 print
>>> print ('hello world') hello world # 只输出一个值 >>> print('koala', 18, 1.55) koala 18 1.55 # 输出多个值需要用逗号隔开print的两种使用方式
1.先写print
print(’koala‘)
2.先写要输出的内容
’koala'.print + Tab键 等同于 print(’koala‘)
拓展:换行符
\r\n:最早期的
\r
\n
格式化输出
把一段字符串里面的某些内容替换掉之后再输出,就是格式化输出
比如要完成“my name is 用户输入的姓名,my age is 用户输入的年龄”的需求
老办法:
>>>name = input('please input your name>>>') # 获取用户的名字 >>>age = input('please input your age>>>') # 获取用户的年龄 >>>print('my name is',name,'my age is',age) # 打印 please input your name>>>koala please input your age>>>18 my name is koala my age is 18可以实现但是麻烦,用格式化输出的办法是:
>>>tep = 'my name is %s my age is %s' # 先定义要打印的格式,这里%s是一个占位符,后续传值替换即可 >>>name = input('please input your name>>>') # 获取用户的名字 >>>age = input('please input your age>>>') # 获取用户的年龄 >>>print(tep % (name,age)) please input your name>>>koala please input your age>>>18 my name is koala my age is 18 # 按照先后顺序一一传值需要注意的是:后续传值的数量需跟占位符的数量相对应,多一个不行,少一个也不行
%s可以给任何类型的数据占位
拓展:
%d:也是一个占位符,只能给数字占位
基本运算符
赋值运算符
name = ‘koala’
先看左边在看右边
算术运算符
加 +
减 -
乘 *
除 /
整除 //
取余 %
幂指数 **python语言对数字的精确的其实并不是很高 需要借助于第三方辅助
其他数据类型也可以使用局部的数学运算符
如:
>>>print('hello' + 'world') helloworld # + 是拼接 >>>print('hello' * 3) hellohellohello # * 是复制增量运算符
x = x + 1 等价于 x += 1
同理:
x -= 1 等价于 x = x - 1
x *= 1 等价于 x = x *1
x /= 1 等价于 x = x /1
...
链式运算符
x = 10 y = x z = y等价于
x = y = z = 10交叉赋值
>>>x = 10 >>>y = 20 >>>x ,y = y , x # 交叉赋值 >>>print(x,y) 20 10解压赋值
>>>name_list = ['jason','egon','tony','kevin'] >>>name1, name2, name3, name4 = name_list # 一一解压赋值给相应的变量 >>>print(name1, name2, name3, name4) jason egon tony kevin等号两边的个数必须一一对应,多一个不行,少一个也不行
想要改变上述情况,可以使用*_
>>>name_list = ['jason','egon','tony','kevin'] >>>name1, name2,*_ = name_list # *_可以用来存放不需要的值 >>>print(name1, name2) jason egon此方法可以用来取开头和结尾的值,中间的值不行
比较运算符
大于 >
小于 <
大于等于 > =
小于等于 <=
等于 ==
不等于 !=
逻辑运算符
与 and
连接多个条件 条件必须都成立
或 or
连接多个条件 一个成立就可以
非 not
取反重点:布尔值为False: 0 None '' [] {}
三者混合使用是存在优先级的,但是我们在混合使用的时候不应该考虑优先级,通过加括号的形式来明确优先级
That’s all ~~

浙公网安备 33010602011771号