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"
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With