1.除法
- 除 /
- 整除 //
- 求余 %
- 商和余数的元组 divmod
a = 9 b = 2 r1 = a/b print(r1) # 4.5 r2 = a//b print(r2) # 4 r3 = a%b print(r3) # 1 r4 = divmod(a,b) print(r4) # (4, 1)
2.输出百分比
方式1:直接使用参数格式化:{:.2%}
{:.2%}
: 显示小数点后2位
显示小数点后2位:
print('percent: {:.2%}'.format(42/50))
不显示小数位:
{:.0%}
,即,将2
改为0
:
print('percent: {:.0%}'.format(42/50))
方式2:格式化为float,然后处理成%格式: {:.2f}%
与方式1的区别是:
(1) 需要对42/50
乘以 100 。
(2) 方式2的%
在{ }
外边,方式1的%
在{ }
里边。
#显示小数点后2位: print('percent: {:.2f}%'.format(42/50*100)) #显示小数点后1位: print('percent: {:.1f}%'.format(42/50*100)) #只显示整数位: #print('percent: {:.0f}%'.format(42/50*100))
a = 3 b = 11 percent = "%.2f%%" % (float(a)/float(b)*100) print(percent) # '27.27%' percent = "{:.2%}".format(float(a)/float(b)) print(percent) # '27.27%'
#默认顺序: print('percent1: {:.2%}, percent2: {:.1%}'.format(42/50, 42/100)) percent1: 84.00%, percent2: 42.0% #指定顺序:{1:.1%}对应第2个参数; {0:.1%}对应第1个参数。 print('percent2: {1:.1%}, percent1: {0:.1%}'.format(42/50, 42/100)) percent2: 42.0%, percent1: 84.0%
float(a)/float(b)
a = 3 b = 11 r = float(a)/float(b) print(r) # 0.2727272727272727