2

The output of following code is

5
3

I am new to Python, could anybody explain to me why?

import sys

def Main():
     str='1+2'
     print eval(str)

class A:
    def __init__(self):
        self.x = 5

a = A()
print a.x

if __name__=="__main__":
    Main()
1

1 Answer 1

10

Python code is evaluated from top-down, not from Main().

The interpreter sees the a = A() line first, and prints a.x which is equal to 5, then it checks for the if condition and prints eval(str) which is 3.

Hence the output,

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

3 Comments

Minor detail. Actually, I believe the interpreter sees the def and class lines first, and it parses the bodies and stores the results in variables. It doesn't evaluate any of the function code while doing so, though.
@jpmc26 : Yes, you are right. The function definitions are evaluated first, but they are not executed until such time that they are called. :)
I wasn't sure, so I did some testing. If you add print 'In class A def!' inside A's definition (and outside the __init__ definition, it actually does get printed first. So code inside the class definition but outside its functions gets executed when the class is parsed.

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.