I am new to Python and I am trying to change the value of an integer while inside of a function. Is there an easy way to do this? I haven’t been able to find much on the subject. Here is my base code.
i = 0
numbers = [2, 7, 8, 14, 15, 38, 27, 9, 77, 10]
print("the value of [5] before the function call is " + str(numbers[5]))
def printArray(numbers, i):
numbers[5] = 48
numbers[0] = 50
for x in numbers:
print(x)
i = 50
printArray(numbers, i)
print("The new value of i is " + str(i))
>Solution :
def printArray(numbers, i):
...
i = 50
This creates i as a new local variable inside the function. It does not, as you found, change the value of i in the caller.
Either make i a global variable, or return a value from the function and assign i to that value in the caller.