请注意我最近才开始学习Python,所以寻找一些非常基本的代码。
我有一个程序需要计算三种形状(立方体,金字塔和椭圆体)的体积,这很容易。问题是,在测试者(用户)为所有三个形状计算了许多不同的体积之后,程序必须输出不同形状的列表以及为每个形状计算的所有体积。
为了更好地解释,假设用户计算3个立方体,2个金字塔和5个椭圆体的体积。当用户键入“退出”而不是新形状时,程序必须输出:
“你已经到了会议的最后阶段。 每种形状的计算体积如下所示: 立方体:(计算的所有卷的列表) 金字塔:(计算所有卷的清单) Ellipsoid :(计算的所有卷的列表)“
提前谢谢! 对于使用Pycharm Edu 3.0.1和Python 3.5.7的记录
while True :
shape =input("Please enter the shape you wish to find the volume of: ")
if shape == "cube":
sideLength = int(input("Please enter side Length: "))
def main():
result1 = round(cubeVolume(sideLength),2)
print ("A cube with side length {} has a volume {}".format(sideLength,result1))
def cubeVolume(sideLength):
volume = sideLength**3
return volume
main()
continue
elif shape == "pyramid":
baseLength = int(input("Please enter the base length: "))
heightLength = int(input("Please enter the height: "))
def main():
result2 = round((pyramidVolume(baseLength,heightLength)),2)
print ("A pyramid with base {} and height {} has a volume {}".format(baseLength,heightLength,result2))
def pyramidVolume(baseLength, heightLength):
volume = ((1/3)*(baseLength**2)*(heightLength))
return volume
main()
continue
elif shape == "ellipsoid":
r1 = int(input("Please enter the longest radius: "))
r2 = int(input("Please enter the smaller radius: "))
r3 = int(input("Please enter the third radius: "))
import math
def main():
result3 = round(ellipsoidVolume(r1,r2,r3),2)
print ('An ellipsoid with a radius of {}, {}, and {} has a volume {}'.format(r1,r2,r3,result3))
def ellipsoidVolume(r1,r2,r3):
volume = ((4/3)*(math.pi))*r1*r2*r3
return volume
main()
continue
elif shape == "quit":
print ("You have come to the end of the session.")
print ("The volumes calculated for each shape are shown below.")
print ("Cube: ") #what I need to find out
print ("Pyramid: ") #same as above
print ("Ellipsoid: ") # again
else:
print ("That is not a proper shape")
continue
答案 0 :(得分:0)
我会用3个列表来做这件事。因此,在while(True)
- 循环之前,您需要定义列表:
cubeList = []
pyramidList = []
ellipsoidList = []
然后在3卷的主要功能中,您可以将结果添加到列表中。例如,对于金字塔,您将拥有以下主要功能:
def main():
result2 = round((pyramidVolume(baseLength,heightLength)),2)
pyramidList.append(result2)
print ("A pyramid with base {} and height {} has a volume {}".format(baseLength,heightLength,result2))
现在,每次用户计算音量时,它都会被添加到3个列表中的一个。作为最后一步,您可以在用户想要退出时打印列表:
print ("Cube: {}".format(cubeList))
print ("Pyramid: {}".format(pyramidList))
print ("Ellipsoid: {}".format(ellipsoidList))
如果你想让列表格式化,你可以这样做:
cs = ""
for ind,el in enumerate(cubeList):
cs += "Shape {} has volume {}".format(ind,el)
print ("Cube: {}".format(cs))