Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to change int value inside function in Python

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading