Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop Counting Scoping In Python

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"
like image 961
Kittystone Avatar asked Jul 14 '16 17:07

Kittystone


1 Answers

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).

like image 78
Athena Avatar answered Oct 26 '22 14:10

Athena