简体   繁体   中英

Passing Variables Simplified

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

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

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.

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