Reputation: 23
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
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