Python计算几何图形面积的示例代码
本文介绍使用Python编写程序计算长方形、正方形、三角形及圆形面积的实例。重点解析如何通过map函数处理多参数输入,以及利用%.2f格式化输出保留两位小数,帮助初学者掌握基础输入输出与数学计算逻辑。
Python计算几何图形面积的示例代码
有开发者提问如何编写程序,根据用户输入的要求输出对应几何形状的面积。
这里简要编写了几行代码,未处理输出异常,主要记录int类型数据的接收过程,具体实现见下图。
该示例涉及两个核心知识点。
第一,计算长方形和三角形面积时,由于需要从终端接收用户的多个参数输入,采用了map(int, raw_input().split())的方式进行处理。
第二,计算圆面积时,若需保留小数点后两位,则使用%.2f格式进行接收和输出。

#!/usr/bin/python
#-*-coding:utf-8 -*-
name = raw_input("Please input your name here : ")
if name == '':
print "we don't like anonymous"
else:
choose = input("Which shape would you like to choose 1:Rectangle, 2:Square, 3:Triangle or 4 Round? :")
if choose == 1:
width, height = map(int, raw_input("Input width and height here, like 5 8 :").split())
print "Area = %d" % (width * height)
elif choose == 2:
length = input("Input width and height here, like 4:")
print "Area = %d" % length ** 2
elif choose == 3:
width, height = map(int, raw_input("Input width and height here, like 5 8 :").split())
print "Area = %d" % (width * height / 2)
elif choose == 4:
diameter = input("Input diameter here like 3 :")
print "Area = %.2f" % (3.14 * (diameter / 2) ** 2)
else:
print "Invalid choose"
以上Python计算几何图形面积的示例代码分享完毕,供读者参考,欢迎支持。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













