2
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?

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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)

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.