【问题标题】:Having trouble executing a function from another Python file从另一个 Python 文件执行函数时遇到问题
【发布时间】:2019-03-11 12:55:58
【问题描述】:

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

【问题讨论】:

  • 你需要在你的 cubeVolume 函数的末尾定义一个return

标签: python list function append


【解决方案1】:

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

【讨论】:

  • 还添加了不满足while循环退出条件的事实
  • @CosmicCat 同样,这是因为volume 被定义为cubeVolume 函数中的局部变量。此函数的调用者无法访问其局部变量,调用者从函数获取值的正确方法是通过其返回值。
  • 只是一个简单的问题...我一直在尝试使用 round(volume, 2) 函数在我声明它之后和打印语句之前对“volume”变量进行舍入,但它没有出于某种原因工作。任何想法
猜你喜欢
  • 1970-01-01
  • 2020-05-19
  • 2022-08-06
  • 2011-12-03
  • 1970-01-01
  • 2019-12-22
  • 2019-09-07
  • 2016-05-10
  • 2014-11-10
相关资源
最近更新 更多