5.1 Python算术运算符
• 假设变量:a=10,b=20
• 注意:Python2.x 里,整数除整数,只能得出整数。如果要得到小数部分,把其中一个整数改成浮点数即可。
5.1.1 Python比较运算符
• 假设变量:a=10,b=20
5.1.2 Python赋值运算符
• 假设变量:a=10,b=20
5.1.3 Python位运算符
• 按位运算符是把数字看作二进制来进行计算。
• 变量 a 为 60,b 为 13,二进制格式如下:
• Python中的按位运算法则如下:
5.1.4 Python逻辑运算符
• 假设变量:a=10,b=20
5.1.5 Python成员运算符
• Python语言支持成员运算符,检测字符串、列表或元组等实例中是否包含某个成员。
5.1.6 is 与 == 区别
• is 用于判断两个变量引用对象是否为同一个,== 用于判断引用变量的值是否相等。
5.2 Python运算符优先级
• 以下表格列出了从最高到最低优先级的所有运算符。
5.3 实验
In:
s1 = '9'
In:
print(s1.isdigit())
print(s1.isnumeric())
out:
True
True
In:
s2 = '五'
print(s2.isdigit())
print(s2.isnumeric())
out:
False
True
In:
s3 = 'V'
print(s3.isdigit())
print(s3.isnumeric())
out:
False
False
In:
dic1 = {'a':[1,2,3],'b':(1,2,3)}
In:
for v in dic1['a']:
print(v)
out:
1
2
3
5.3.1 比较运算符
In:
1 == 1
out:
True
In:
1 != 2
out:
True
In:
a1 = 1
for i in range(10):
a1 += 1
a1
out:
11
In:
print(3<<2) #左移*2 ,右移动/2
out:
12
In:
b1 = 4
In:
if a1 > 5 and b1 >3:
print(1)
if (a1 > 5 and b1 >3) == True:
print(1)
out:
1
1
In:
if a1 > 5 or b1 >10:
print(1)
out:
1
In:
if not(a1 > 5 and b1 >3):
print(1)
else:
print(0)
out:
0
In:
a = [1,2,3]
b =a
print(id(b),id(a))
out:
2169969669448 2169969669448
In:
b is a
out:
True
In:
b = a[:]
print(id(b))
out:
2169976304584
In:
b is a
out:
False
In:
b == a
out:
True
In:
if a1 > 5 and b1 >3 or 1 > 2:
print(1)
else:
print(0)
out:
1
In:
if a1 > 50 and (b1 >3 or 1 > 2):
print(1)
else:
print(0)
out:
0
5.3.2 输入圆的半径计算计算周长和面积。
输出要求:
- 输入半径:2
- 周长: 12.57
- 面积: 12.57
In:
import math
rad = float(input('输入半径:'))
# per = round(2 * math.pi * rad,2)
# area = round(math.pi * rad**2,2)
per = 2 * math.pi * rad
area = math.pi * rad**2
print("周长:%.2f" % per)
print("面积:%.2f" % area)
out:
输入半径:2
周长:12.57
面积:12.57
闰年判断
- 整除4并且不能被100整除
- 被400整除
In:
year = int(input('输入年份:'))
if year % 4 == 0 and year % 100 != 0 or year % 400 ==0:
print("{}是闰年".format(year))
else:
print("{}不是闰年".format(year))
out:
输入年份:2020
2020是闰年