python 数学操作符

时间:2022-08-30 17:48:29

python 数学操作符  

优先级从高到低



print("2 ** 3 = %d" % 2 ** 3) 2 ** 3 = 8
print("7 % 2 = {}".format(7 % 2)) 7 % 2 = 1
print('7 %% 2 = %d' % (7 % 2)) 7 % 2 = 1
print("7 // 2 = %d" % (7 // 2)) 7 // 2 = 3
print("7 / 2 = %s" % (7 / 2)) 7 / 2 = 3.5
print("2 * 3 = %d" % (2 * 3))   2 * 3 = 6
print("2 * 3 = %d" % 2 * 3) 2 * 3 = 22 * 3 = 22 * 3 = 2
print("3 - 2 = %d" % (3 - 2)) 3 - 2 = 1
print("3 + 2 = %d" % (3 + 2))   3 + 2 = 5

优先级的重要性,操作符的执行顺序从左到右

没有加括号,执行结果是不一样的
print("2 * 3 = %d" % 2 * 3)        2 * 3 = 22 * 3 = 22 * 3 = 2
print("2 * 3 = %d" % (2 * 3))    2 * 3 = 6

+、-、*、/、//、%和**是数学操作符,+和*是字符串操作符