简体   繁体   中英

Function call as argument to print in python 3.x

a = 0
def f():
    global a
    a = 1
    print(a)
print(a, f(), a)

The output of the above code turns out to be the following:

1
0 None 1

Why is the function f called before printing the first argument a ? Why is the value of the first argument 0 , even after the function call?

What you get as output is:

1
0 None 1

When you call print() it computes the elements to be printed first. As you have print(a) inside your f() what you get first is 1 . Then, it starts printing. The value of a is 0 before you call the function. When you print a function that doesn't return anything, you get None . As you change the value globally, you get 1 at the end.

Your function is printing, not returning, so there's no value when f() is called.

Basically, the order of things is this: Interpreter sees print, evaluates a (it's zero), then sees it needs to evaluate f() before it knows what to print, calls f , which gets you the 1 printed above, then evaluates a again (it's now 1). The line is printed.

It is not 0 after the function call, but before it. The first a in your second print statement is passed in before f is called. And why do you print f ()? It returns nothing (None)

Python will run the a = 0 line first, then define - but NOT run - the function f() , and then run the print(a,f(),a) call. Therefore, the first print will be a after it has been defined with value 0, then the second print will call the function f() , which does not have a return and therefore will print None . Finally, you will print the value that f() assigned to a , which will be 1.

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