0

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
Cristian Ciupitu
  • 20,270
  • 7
  • 50
  • 76
  • Scope... [Short Description of Python Scoping Rules](http://stackoverflow.com/a/292502/1762224) – Mr. Polywhirl Nov 14 '13 at 00:33
  • @user2989980 Welcome to SO, mate. To make your membership here useful and enjoyable, please read relevant help sections here: http://stackoverflow.com/help/asking. Otherwise most of your questions will be closed and probably downvoted. Also, try to spend some time trying to resolve the problem yourself by searching for similar questions and simply playing with your code. This question is a very typical one, has been asked many many times and surely you would have learned the problem after reading some introductory python tutorials on functions and scope. – sashkello Nov 14 '13 at 00:55

4 Answers4

3

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

binarysmacker
  • 982
  • 2
  • 9
  • 20
1

because i=5 and j=9 were assigned outside the scope of the function so they were only changed in the function but when you printed them they were outside the function so they were never actually changed

more on variable scope

Serial
  • 7,925
  • 13
  • 52
  • 71
1

When you change a value inside a function the change is not reflected outside.

In a slightly different presentation manner, in def function(string, i, j): we have 3 formal parameters, one of whom is i. I can call if with function("str", 3, j) and there would be no i in the caller to be updated.

Mihai Maruseac
  • 20,967
  • 7
  • 57
  • 109
0

Scalar/immutable types (ints, floats, strings) are not modified by functions, outside a function itself.

Composite types are modified in a limited sense though. EG, if you pass a dictionary to a function and change it in the function, then elements of the dictionary can be modified, but if you assign a different dictionary to the same variable, then the changes will not be seen outside the function. IOW, you can change what the dictionary contains, not the dictionary itself.

dstromberg
  • 6,954
  • 1
  • 26
  • 27