0
age = 11

def agePrint():

    age += 1

    print(age)

agePrint()

--- This code makes an error. It is obvious. Because age is outside the function agePoint(). But... if age type is a list...

age = [11, 12, 13]

def agePrint():

    age[0] = 15

    print(age)

agePrint()

This code works well. I want to know the reason. I am waiting for your answer.

Many thanks

bilke
  • 415
  • 3
  • 6
JM SG
  • 1
  • 2
    `age +=` contains an *assignment to a variable*, `age[0] =` is just an object mutation, not a reassignment. Outer variables are always available to *read* inside nested functions, `print(age)` or `age[0]` works inside the function in any case. It's the assignment that breaks it. Read [the duplicate](https://stackoverflow.com/a/9264845/476) for why. – deceze Jan 21 '21 at 10:35

1 Answers1

0

This behaviour has to do with the variable age being an integer or a list.

The restriction involved goes like "a global variable can't be modified inside a function, unless explicitly allowed by using the keyword global". In the first case, age is of type int, so it stores the integer value as is. However, in the second case, age is of type list, so it actually stores the pointer or reference to a list-like object. When you change an element of that list, you're only changing an attribute of that object, but not the variable itself (age conserves its value). In order to change the variable, in that latter case, you would have to assign a different value directly or somehow try to change the pointer or reference.

This can be confusing if you don't know about object-oriented programming or you're not aware of python using objects, but basically all variables in python which aren't integers, floats or booleans are objects.

David
  • 453
  • 1
  • 4
  • 14
  • *Every* value is an object, even integers, floats and bools. However, there's simply no way to *mutate* them. They don't expose any methods that would allow you to *mutate* an int, hence you can only reassign them. – deceze Jan 21 '21 at 10:47