所以我编写了一个简单的程序来根据用户输入计算立方体的体积。我有一个 main.py 和一个volume.py。在 main.py 中,我简单地调用相应的函数cubeVolume。但是,当我尝试将volume.py 中生成的立方体体积 append 到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
最佳答案
volume
是 cubeVolume
函数的局部变量,在函数外部无法访问。您应该让您的 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))
关于python - 从另一个 Python 文件执行函数时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52675402/