使用Python实现计算器功能

来源:互联网 发布:2017最污的网络词 编辑:程序博客网 时间:2024/06/06 02:20

实现目标:使用Python完成,输入两个数,得到加减乘除余结果的功能,其中结果输出使用不同的格式。

Python版本为3.6.0

1. 定义两个变量a,b,使用键盘输入的方式。python的2.x版本中键盘输入有两种方式可以实现:raw_input(),input(),在3.X版本中两者合并为一个,只支持input().

2.  输出结果:

(1)   输出string型的结果

print("A+B = %s"%(a+b))        # output string
(2)  输出int型的结果:默认格式,占位符格式,填充占位符格式,靠左格式

print("A-B = %d"%(a-b))        # output intprint("A-B = %4d"%(a-b)) print("A-B = %04d"%(a-b))   print("A-B = %-4d"%(a-b))  

结果:a=7,b=3

A-B = 4A-B =    4A-B = 0004A-B = 4 

(3)  输出为浮点数类型:默认格式,限制小数位数格式,占位符及限制小数位数格式

print("A*B = %f"%(a*b))        # output floatprint("A/B = %.2f"%(a/b))      # output float of two decimal placesprint("A/B = %05.2f"%(a/b))      # output float of two decimal places

结果:a=7,b=3

A*B = 21.000000
A/B = 2.33
A/B = 02.33

3. 全部实现,开发工具为pycharm


# calculatea = int(input("Please input number A:"))b = int(input("Please input number B:"))print("A+B = %s"%(a+b))        # output stringprint("A-B = %d"%(a-b))        # output intprint("A*B = %f"%(a*b))        # output floatprint("A/B = %.2f"%(a/b))      # output float of two decimal placesprint("A%B"+" = %06d"%(a%b))    # output int of 6 bit placeholder filled with 0print("A与B和是%s,差是%d,乘积是%02.2f,商是%-4.2f,余数是%03d"%(a+b,a-b,a*b,a/b,a%b))