简体   繁体   中英

Having trouble executing a function from another Python file

So im writing a simple program to calculate volume for a cube based on user input. I have a main.py and a volume.py. In the main.py, I simply call the respective function cubeVolume. However when I try to append the resulting cube volume from volume.py into a list in main.py called cubeList, I get an undefined error. How can I fix this?

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

Here is the volume.py file

#volume.py
import math

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

Heres my output:

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 is a local variable to the cubeVolume function and is inaccessible outside of it. You should make your cubeVolume return volume so that the main program can have access its value:

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

And in the main program, change:

cubeVolume(cubeSide)
cubeList.append(volume)

to:

cubeList.append(cubeVolume(cubeSide))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM