简体   繁体   中英

Calling variables in Python (local vs global)

The below works and gives 8:

def mypow(a,b):
    c=a**b
    print (c)

mypow(2,3)

But the below doesn't:

def mypow(a,b):
    c=a**b

mypow(2,3)

I understand that in the former we print but since the latter doesn't give an error message (nor does it give a result), what is actually happening in the latter?

in

def mypow(a,b):
    c=a**b

mypow(2,3)

after function executed; all data inside the function destroy. if you want to see anything on your screen after function is executed; either use print or return .

In the end of any function you have multiple choices.

1- return . return the output. when you return the output you receive it after function executed without error eg: d = func(any_value) , if you specified the return value in func you will receive it and store it in d . if you don't specify the return statement in the function the function will return None .

2- print . print anything. this is what you did in your first function. in this case you get printed stuff in your screen, and you function return None , so you can't hold the output (a printed value) in any variable or use it anywhere else.

3- global . assign to global. when you need this option you create a variable outside of your function say my_variale=5 , and in the first line of your function you write gloabl my_variable . say the function contain 5 lines, in line #3 you did my_variable=7 . after function is executed and destroyed all values within the function; when you check my_variable you will see it contains value of 5 .

You can replace print with return for your function and get the same result

def mypow(a,b):
    c=a**b
    return c

mypow(2,3)

Variables nested in functions are treated as local variables unless you add global before the variable name.

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