简体   繁体   中英

Error when importing the returned value of a function in a different module using Python

I have a file ( calculations ) with a defined function called number , whose return value is i when executed. Now, I have defined a function in a different file and want to print the value i . However, when I try to "import" i , I get an error message saying that i cannot be imported.

This is my code (where i is supposed to be imported from the function number that is defined in calculations )

import calculations

def myfunction():
    calculations.number()
    print(calculations.i)

Apparently, executing myfunction() without the print(calculations.i) statement works successfully. But when I try to import i following the same method, it doesn't. I have also tried using from calculations import i , though it doesn't work either. It probably has to do with the fact that the last time it was "mentioned" in the number() function was as return i (though this might not be the problem), or with the fact that it's not part of the calculations file itself, but it's within the definition of one of functions stored in that file...

In any case, what's happening and how can I import this value?

Edit: This is the code in the file calculations :

def number():
    a = 2
    i = 0
    while a < 100
        a = a + 2
        i = i+1
    return i

You can not import variables which is local to the function, below are some approach with which you can use that variable

Solution 1:

This is the code in the file calculations:

def number():
    a = 2
    i = 0
    while a < 100
        a = a + 2
        i = i+1
    return i

You can call number inside myfunction and assign it to some variable let's say i

import calculations

def myfunction():
    i = calculations.number()
    print(i)

Solution 2:

Or you can do this:

This is the code in the file calculations:

i = number()
def number():
    a = 2
    j = 0
    while a < 100
        a = a + 2
        j = j+1
    return j

Your myfunction

import calculations
def myfunction():
    print(calculations.i)

Solution 3:

Or you can do this:

This is the code in the file calculations:

global i = 0
def number():
    a = 2
    while a < 100
        a = a + 2
        i = i+1
    return i

Your myfunction

import calculations
def myfunction():
    print(calculations.i)

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