首页 > 解决方案 > (初学者)在音量计算器上输入“退出”时出错

问题描述

我对python相当陌生。只是想知道为什么当我输入“退出”时我的音量计算器会出错。所有其他方程,如立方体、金字塔和椭圆体都可以工作。但是当我输入“退出”或“q”给我输入的答案时,出现了错误。

这是代码

 def cubeVolume() :
    sideLength = float(input('What is the length of one side of the cube?: '))
    volume = sideLength ** 3
    cubeVolumeList.append(round(volume, 2))     # Adds the rounded volume to the given list
    cubeVolumeList.sort()
    print('\nThe volume of a cube with a side length of %.1f is %.1f' % (round(sideLength, 2), round(volume, 2)))

def pyramidVolume() :
    base = float(input('What is the base length of the pyramid?: '))
    height = float(input('What is the height of the pyramid?: '))
    volume = (1 / 3) * (base ** 2) * height
    pyramidVolumeList.append(round(volume, 2))
    pyramidVolumeList.sort()
    print('\nThe volume of a pyramid with a base length of %.1f and a height of %.1f is %.1f' % (round(base, 2), round(height, 2), round(volume, 2)))

def ellipsoidVolume() :
    from math import pi
    r1 = float(input('What is the value of radius 1?: '))       # r1: radius 1, r2: radius 2, etc.
    r2 = float(input('What is the value of radius 2?: '))
    r3 = float(input('What is the value of radius 3?: '))
    volume = (4 / 3) * pi * r1 * r2 * r3
    ellipsoidVolumeList.append(round(volume, 2))
    ellipsoidVolumeList.sort()
    print('\nThe volume of an ellipsoid with a radius 1 of %.1f, a radius 2 of %.1f, and a radius 3 of %.1f is %.1f' % (round(r1, 2), round(r2, 2), round(r3, 2), round(volume, 2)))

# Initialization of empty lists

cubeVolumeList = []
pyramidVolumeList = []
ellipsoidVolumeList = []

# Creating the main function to be called at the end of the program

def main() :
    shapeInput = (input('Please enter shape (quit/q, cube/c, pyramid/p, ellipsoid/e):')).lower()

    # Creation of validity loop

    valid = False
    while not valid :
        if shapeInput in ['c', 'cube']:
            cubeVolume()
            print()
            shapeInput = (input('Please enter shape (quit/q, cube/c, pyramid/p, ellipsoid/e):')).lower()
        elif shapeInput in ['p', 'pyramid']:
            pyramidVolume()
            print()
            shapeInput = (input('Please enter shape (quit/q, cube/c, pyramid/p, ellipsoid/e):')).lower()
        elif shapeInput in ['e', 'ellipsoid'] :
            ellipsoidVolume()
            print()
            shapeInput = (input('Please enter shape (quit/q, cube/c, pyramid/p, ellipsoid/e):')).lower()
        elif shapeInput in ['q', 'quit'] :
            valid = True
        else :
            print('\nInvalid input! Please try again.')
            print()
            shapeInput = (input('Please enter shape (quit/q, cube/c, pyramid/p, ellipsoid/e):')).lower()

    # Output after user enters "quit"

    if len(cubeVolumeList) != 0 or len(pyramidVolumeList) != 0 or len(ellipsoidVolumeList) != 0 :
        print()
        print('You have come to the end of the session.')
        print('The volumes calculated for each shape are shown below.')

        print('cube: ', end = '')
        i = 0
        while i < len(cubeVolumeList) - 1 :
            print(str(cubeVolumeList[i]) + ',' + ' ', end = '')
            i = i + 1
        print(cubeVolumeList[len(cubeVolumeList) - 1])

        print('pyramid: ', end = '')
        i = 0
        while i < len(pyramidVolumeList) - 1 :
            print(str(pyramidVolumeList[i]) + ',' + ' ', end = '')
            i = i + 1
        print(pyramidVolumeList[len(pyramidVolumeList) - 1])

        print('ellipsoid: ', end = '')
        i = 0
        while i < len(ellipsoidVolumeList) - 1 :
            print(str(ellipsoidVolumeList[i]) + ',' + ' ', end = '')
            i = i + 1
        print(ellipsoidVolumeList[len(ellipsoidVolumeList) - 1])

    else :
        print('\nYou have come to the end of the session.')
        print('You did not perform any volume calculations')

main()  # Calling the main function

不知道为什么当我输入“退出”时出现错误。帮助将不胜感激。谢谢

错误信息是

Traceback (most recent call last):
  File "C:/Users/aman/PycharmProjects/Assign1.py/main.py", line 95, in <module>
    main()  # Calling the main function
  File "C:/Users/aman/PycharmProjects/Assign1.py/main.py", line 82, in main
    print(pyramidVolumeList[len(pyramidVolumeList) - 1])
IndexError: list index out of range

标签: pythonpython-3.xpycharmindex-error

解决方案


您处理用户进入会话而不使用以下行计算某些值的情况: if len(cubeVolumeList) != 0 or len(pyramidVolumeList) != 0 or len(ellipsoidVolumeList) != 0 : 问题是此检查仅告诉您至少计算了一个卷,但没有计算出哪一个。该块中的后续代码假定计算了所有体积。要修复,您可以添加单独的检查以查看哪个列表为空:

...

    if len(cubeVolumeList) != 0 or len(pyramidVolumeList) != 0 or len(ellipsoidVolumeList) != 0 :
        print()
        print('You have come to the end of the session.')
        print('The volumes calculated for each shape are shown below.')

        print('cube: ', end = '')
        if len(cubeVolumeList) == 0:
            print('NIL')
        else:
            i = 0
            while i < len(cubeVolumeList) - 1 :
                print(str(cubeVolumeList[i]) + ',' + ' ', end = '')
                i = i + 1
            print(cubeVolumeList[len(cubeVolumeList) - 1])

        print('pyramid: ', end = '')
        if len(pyramidVolumeList) == 0:
            print('NIL')
        else:
            i = 0
            while i < len(pyramidVolumeList) - 1 :
                print(str(pyramidVolumeList[i]) + ',' + ' ', end = '')
                i = i + 1
            print(pyramidVolumeList[len(pyramidVolumeList) - 1])

        print('ellipsoid: ', end = '')
        if len(ellipsoidVolumeList) == 0:
            print('NIL')
        else:
            i = 0
            while i < len(ellipsoidVolumeList) - 1 :
                print(str(ellipsoidVolumeList[i]) + ',' + ' ', end = '')
                i = i + 1
            print(ellipsoidVolumeList[len(ellipsoidVolumeList) - 1])

    else :
        print('\nYou have come to the end of the session.')
        print('You did not perform any volume calculations')

推荐阅读