Click here to Skip to main content
15,897,226 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Python
x=90
def harry():
    x=20
    def rohan():
        global x
        x=88

     print("before calling rohan",x)
     rohan()
     print("after calling rohan", x)

harry()
print(x)


What I have tried:

why this is printing 90 instead of 88?
Posted
Updated 23-Jul-20 20:57pm
v3

Output of above:
('before calling rohan', 20)
('after calling rohan', 20)
88

Execution sequence:
1. harry() called
2. print("before calling rohan",x) => x=local x value that is not modified so far => 20
3. rohan() called => updates global x value to 88
4. print("after calling rohan", x) => local x value is still as it was - not modified => 20
5. print(x) called => global x value is checked which was set to 88 by rohan() => 88
 
Share this answer
 
Comments
Member 14897676 24-Jul-20 8:25am    
thanks sir!
Sandeep Mewara 24-Jul-20 9:14am    
Welcome
Because your indentation doesn't match:
Python
def harry():
    x=20
    def rohan():
        global x
        ...

     print("before calling rohan",x)
     ...
You have extra whitespace before the "print" instruction.
As a result, it doesn't run.
Remove those from the three lines and it prints "88"

Don't mix tabs and spaces: set your editor to always replace tabs as it'll save you a LOT of grief later. Python indentation is very important, and a TAB is not the same as a SPACE - if you don't "just use spaces" then what looks identical turns out not to be as far as Python is concerned.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900