0

I am working on a project, but I need to pass variables between functions and I do not know how. I am not very good at python at all. I just started learning it like a month ago. Anyhow I just want to know the simplest way to pass a variable between functions.

Can I just do this?

def a():
    variable1 = 0
    answer = raw_input()
    if answer == "a":
       print "Correct"
       b()

def b():
    #Variable1 should now be here also right?
    a()
msvalkon
  • 11,887
  • 2
  • 42
  • 38
user3448743
  • 43
  • 3
  • 10
  • Some pointer on "namespace" if you want to do more python: http://bytebaker.com/2008/07/30/python-namespaces/ https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces – fredtantini Mar 30 '14 at 21:07

2 Answers2

2

Add a parameter to your function b.

def b(argument1):
   print 'This is function b(), argument1=', argument1

def a():
    # call func b, passing it 42 as an argument
    b(42)

In Python you can use global variables, but this is not the recommended way of doing things. Global variables should generally be avoided.

def b()
    print 'This is function b(), globalVar1=', globalVar1

def a()
    global globalVar1

    globalVar1 = 88

    b()
Community
  • 1
  • 1
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
1

The easiest way to pass a variable between functions is to define the necessary function to accept an argument. Check out functions -part in the official tutorial

In your case you want to pass variable1 to b. Define b as such:

def b(var):
     print var
     # Whatever else you want to do..

def a():
    variable1 = 0
    answer = raw_input()
    if answer == "a":
       print "Correct"
       b(variable1)

Your original code does not work because variables inside functions are local to those functions. Using function arguments is the correct way of doing what you want.

msvalkon
  • 11,887
  • 2
  • 42
  • 38