mousepotato
mousepotato

Reputation: 23

Python code evaluation order?

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

Upvotes: 2

Views: 292

Answers (1)

Sukrit Kalra
Sukrit Kalra

Reputation: 34533

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

Upvotes: 10

Related Questions