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.