无法从另一个Python文件执行功能

时间:2018-10-06 03:14:56

标签: python list function append

因此,我正在编写一个简单的程序来根据用户输入来计算多维数据集的体积。我有一个main.py和一个volume.py。在main.py中,我只调用了相应的功能cubeVolume。但是,当我尝试将来自volume.py的多维数据集卷追加到main.py中名为cubeList的列表中时,出现未定义的错误。我该如何解决?

#main.py
from volume import cubeVolume
import math

cubeList = []
userInput = str(input("Enter the shape you wish to calculate the volume for: "))
userInput = ''.join(userInput.split()).lower().capitalize()

while userInput != "Q" or userInput != "Quit":
    if userInput == "C" or userInput == "Cube":
        cubeSide = int(input("Enter the side length for the Cube: "))
        cubeVolume(cubeSide)
        cubeList.append(volume)

这是volume.py文件

#volume.py
import math

def cubeVolume(side):
    volume = side**3
    print("The volume of the cube with side length {} is: {}".format(side, volume))

以下是我的输出:

Enter the shape you wish to calculate the volume for: cube
Enter the side length for the Cube: 3
    The volume of the cube with side length 3 is: 27
    Traceback (most recent call last):
      File "/Users/User/Desktop/folder2/main.py", line 14, in <module>
        cubeList.append(volume)
    NameError: name 'volume' is not defined

1 个答案:

答案 0 :(得分:2)

volumecubeVolume函数的局部变量,在其外部不可访问。您应该使cubeVolume返回volume,以便主程序可以访问其值:

def cubeVolume(side):
    volume = side**3
    print("The volume of the cube with side length {} is: {}".format(side, volume))
    return volume

在主程序中,更改:

cubeVolume(cubeSide)
cubeList.append(volume)

收件人:

cubeList.append(cubeVolume(cubeSide))