Function - Why does Python print this

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

Can someone explain why this Python code:

def function(string, i, j): 
    if (i < j):
        i = i+1
        string1 = string[i:j] return string1
    else:
        return string
# main
string = "four score and seven years ago" 
i = 5
j = 9
stringslice = function(string, i, j) 
print (stringslice)
print (i, j)

prints:

cor
5 9

I thought it should print the following:

cor
6 9

Answers

The i that is being incremented is local to that function, and is not effecting the i of your main code. So when you print i its the original i

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/19966990/why-does-python-print-this

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils