python - 从另一个 Python 文件执行函数时遇到问题

标签 python list function append

所以我编写了一个简单的程序来根据用户输入计算立方体的体积。我有一个 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

最佳答案

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))

关于python - 从另一个 Python 文件执行函数时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52675402/

相关文章:

python - 同时使用调试器和 curses?

Python单元测试断言复杂字典

python - 使用 BeautifulSoup4 (python 3.4) 删除所有 HTML 标签

python - Python 中将字节转换为 int32_t 列表的最快方法

R 函数没有返回值

python - Python 每秒增加消息数

xcode - 当键盘可见/不可见时显示/隐藏 navigationBarItems | SwiftUI

javascript - 从具有 anchor 和图像标签的输入更新列表的 html

function - Elixir:函数的结构默认值

r - 如何跨运行应用函数