Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 298
mousepotato Avatar asked Jul 25 '26 22:07

mousepotato


1 Answers

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
like image 181
Sukrit Kalra Avatar answered Jul 28 '26 13:07

Sukrit Kalra