我是一名编程初学者(从未编程过)我已经获得了一项任务(学校)制作一个程序,要求用户提供一个形状,然后根据给定的尺寸计算该形状的体积。用户。但是如果用户没有输入“退出”,程序应该不断询问用户的形状并继续计算卷,当用户输入“退出”时,程序就会打印出卷列表计算。这三种形状是立方体,金字塔和椭圆体。
例如,如果用户键入立方体,立方体,金字塔,金字塔,椭圆体然后退出(以及计算体积所需的维度),则程序应打印出来:
多维数据集卷数为4,5
金字塔卷数为6,7
椭圆体积为8
注意:这些数字仅供参考。
我成功(有点)让程序注意到错误,并且程序反复询问用户形状和计算量,直到输入“退出”,但是我无法弄清楚如何实现“示例列表”答案的类型“,有没有办法做到这一点?
这是我的代码(它可能不是很好,但它是我现在作为初学者和我们迄今为止所教授的内容所能做的最好的代码):
import math
shapeName = input ("Please enter the shape you want to calculate the volume
of:").upper()
def volumeCube (side):
Volume = 0
Volume = side**3
print ("The Volume of the cube is", Volume)
return;
def volumePyramid (baseSideLength,height):
Volume = 0
Volume = round((1/3)*(baseSideLength**2)*height,1)
print ("The volume of the pyramid is", Volume)
return;
def volumeEllipsoid (radius1,radius2,radius3):
Volume = 0
Volume = round((4/3)*math.pi*radius1*radius2*radius3,1)
print ("The volume of the ellipsoid is", Volume)
return;
while shapeName != "QUIT":
while shapeName in ["CUBE","PYRAMID","ELLIPSOID","QUIT"]:
if shapeName == "CUBE":
side = int(input("Please enter the length of the sides:"))
volumeCube(side)
shapeName = input("Please enter the shape you want to calculate the volume of:").upper()
elif shapeName == "PYRAMID":
baseSideLength = int(input("Please enter the lengths of the side of the base:"))
height = int(input("Please enter the height of the pyramid:"))
volumePyramid(baseSideLength, height)
shapeName = input("Please enter the shape you want to calculate the volume of:").upper()
elif shapeName == "ELLIPSOID":
radius1 = int(input("Please enter the first radius:"))
radius2 = int(input("Please enter the second radius:"))
radius3 = int(input("Please enter the third radius:"))
volumeEllipsoid(radius1, radius2, radius3)
shapeName = input("Please enter the shape you want to calculate the volume of:").upper()
elif shapeName == "QUIT" :
print ("\nYou have come to the end of the session. \nThe volumes calculated for each shape are shown below:")
volumeCube (side)
volumePyramid(baseSideLength, height)
volumeEllipsoid(radius1, radius2, radius3)
exit()
else:
print ("Error")
shapeName = input("Please enter the shape you want to calculate the volume of:").upper()
else:
print ("\nyou have come to the end of the session. \nYou have not performed any volume calculations.")
这是我的原始代码,它没有创建列表,所以我试图通过改变函数的“立方体”部分来测试它,如:
def volumeCube (side):
Volume = 0
VolumeCubeList = []
VolumeCubeList.append (side**3)
print (VolumeCubeList)
return;
但这只返回了一个答案(例如,如果第一个立方体的边长为3,第二个立方体的边长为4,则返回的答案仅为[64]) 有没有办法来解决这个问题?还有什么我做错了吗?
答案 0 :(得分:1)
似乎问题是因为在执行以下代码时未定义某些变量:
time
现在,为什么它不起作用?
因为,例如,如果用户不想计算volumePyramid,你仍然在调用volymePyramid(BaseSideLenght,height),从不定义basesideLenght和height,因为它们从未被用户输入。 (和其他形状一样)
你可以做的是拥有一个字符串列表,每次计算一个卷时都存储一个卷,并在程序结束时显示这个列表;)
以下是如何操作:
elif shapeName == "QUIT" :
print ("\nYou have come to the end of the session. \nThe volumes calculated for each shape are shown below:")
volumeCube (side)
volumePyramid(baseSideLength, height)
volumeEllipsoid(radius1, radius2, radius3)
exit()