2016-10-26 2 views
0

Обратите внимание, что я недавно начал изучать Python, так что ищет довольно простой код.Как перечислять все входы, рассчитанные?

У меня есть программа, которая должна рассчитать Объемы трех типов фигур (куб, пирамида и эллипсоид), что достаточно просто. Проблема в том, что после того, как тестер (пользователь) рассчитал много разных томов для всех трех фигур, программа должна вывести список разных фигур и всех томов, которые он рассчитал для каждой фигуры.

Чтобы лучше объяснить, скажем, пользователь вычисляет объемы из 3 кубов, 2 пирамид и 5 эллипсоидов. Когда пользователь вводит в «Выход» вместо новой формы, программа затем должна выход:.

«Вы пришли к концу сессии Объемы Рассчитанные для каждой формы приведены ниже: Кубик: (список всех объёмов) Пирамида: (Перечисление всех объемов) Эллипсоид: (Перечисление всех объемов)) «

Спасибо заранее! Для записи с помощью 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

Я хотел бы сделать это с 3-х листах. Поэтому, прежде чем ваши while(True) -loop вы определяете списки:

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)) 
Смежные вопросы