简体   繁体   中英

Problem with calling a variable from one function into another

I am trying to call a variable from one function into another by using the command return , without success. This is the example code I have:

def G():
    x = 2
    y = 3
    g = x*y
    return g

def H():
    r = 2*G(g)
    print(r)
    return r
H()

When I run the code i receive the following error NameError: name 'g' is not defined

Thanks in advance!

Your function def G(): returns a variable. Therefore, when you call it, you assign a new variable for the returned variable.

Therefore you could use the following code:

def H():
    G = G()
    r = 2*G
    print (r)

You don't need to give this statement:

return r

While you've accepted the answer above, I'd like to take the time to help you learn and clean up your code.

NameError: name 'g' is not defined

You're getting this error because g is a local variable of the function G()

Clean Version:

def multiple_two_numbers():
    """
      Multiplies two numbers

      Args:
        none

      Returns:
        product : the result of multiplying two numbers
    """

    x = 2
    y = 3
    product = x*y
    return product


def main():

    result = multiple_two_numbers()
    answer = 2 * result
    print(answer)

if __name__ == "__main__":
    # execute only if run as a script
    main()

Problems with your code:

  1. Have clear variable and method names. g and G can be quiet confusing to the reader.

  2. Your not using the if __name__ == "__main__":

  3. Your return in H() unnecessary as well as the H() function.

  4. Use docstrings to help make your code more readable.

Questions from the comments :

I have one question what if I had two or more variables in the first function but I only want to call one of them

Your function can have as many variables as you want. If you want to return more than one variable you can use a dictionary(key,value) List, or Tuple. It all depends on your requirements.

Is it necessary to give different names, a and b , to the new variables or can I use the same x and g ?

Absolutely! Declaring another variable called x or y will cause the previous declaration to be overwritten. This could make it hard to debug and you and readers of your code will be frustrated.

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