6

I'm trying to figure out how this code works. How is i accessible outside the for loop?

# Palindrome of string
str=raw_input("Enter the string\n")
ln=len(str)
for i in range(ln/2) :
    if(str[ln-i-1]!=str[i]):
        break
if(i==(ln/2)-1):         ## How is i accessible outside the for loop ? 
    print "Palindrome"
else:
    print "Not Palindrome"
Athena
  • 3,200
  • 3
  • 27
  • 35
Kittystone
  • 661
  • 3
  • 9
  • 28
  • 3
    for loops do not have their own namespace. [Short Description of Python Scoping Rules](http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules) – Moses Koledoye Jul 14 '16 at 17:46
  • 1
    `i` is accessible because loop variables stay in the current scope with their last value unless you assign something else to the name. – Morgan Thrapp Jul 14 '16 at 17:46
  • 2
    Why? How or what are you implementing this for? It is overly complex for what it does. `mystr == mystr[::-1]` – Nick Jul 14 '16 at 17:46
  • 3
    Good job actually asking about the specific aspect of the code you don't understand! That makes your question way more answerable. – user2357112 Jul 14 '16 at 17:48
  • Side note: do not use `str` as a variable name, as you are shadowing the built-in [str](https://docs.python.org/3/library/stdtypes.html#str) – idjaw Jul 14 '16 at 17:49
  • Also i want understand the logic here , i am not able to get the if condition clearly , suppose my input is (nitin) so can someone guide me how its being evaluated , since the for loop will be run from i=0 to i = 2 – Kittystone Jul 14 '16 at 17:55

1 Answers1

1

This is part of Python. Variables declared inside for loops (that includes loop counters) won't decay until they fully leave scope.

Take a look at this question:

Scoping In Python For Loops

From the answers:

for foo in xrange(10):
    bar = 2
print(foo, bar)

The above will print (9,2).

Community
  • 1
  • 1
Athena
  • 3,200
  • 3
  • 27
  • 35