Home > Software design >  I think it's a basic question but I don't get why I get 0 in this function
I think it's a basic question but I don't get why I get 0 in this function

Time:02-08

a = 0

def add(number):
    number  = 1
    return number

for i in range(20):
    add(a)

print(a)

I'm wondering why I get 0 for the print(a) call in the last line. I put 0 for the first loop of the add()function and it should return 1 and so on in the for loop. What am I missing?

CodePudding user response:

I think you're just missing assigning the return value of add() back to a. Without the assignment, a never changes because function arguments are passed by value, not reference.

a = 0

def add(number):
    number  = 1
    return number

for i in range(20):
    a = add(a)

print(a)

CodePudding user response:

it seems you aren't actually changing the value of a, try changing your for loop to look something like this:

for i in range(20):
    a = add(a)

To make use of the return keyword, make sure you understand that it sends back a value to the main program, treat it like another variable.

CodePudding user response:

When you pass an int to a function, you're basically passing a copy of it. So your function adds 1 to a copy of a and returns it, but there's nothing there to catch the returned value.

When you pass a list or dict to a function, you're passing a reference to the original object, though. If you change it inside your function it changes thoughout your code:

a = 0
b = [0]
c = {"engelbert": 0}

def add(number, lst, dct):
    number  = 1
    lst[0]  = 1
    dct["engelbert"]  = 1
    # No return statement:
    # Function returns `None` by default

for i in range(20):
    add(a, b, c)

print(a, b, c)
# 0 [20] {'engelbert': 20}

CodePudding user response:

You just created an a value and print it out. You need to run function add first, to update value of a, or create new value from a then print it.

There maybe an example for you:

a = 0

def add(number):
    number  = 1
    return number

print(add(a))

If you want to print 0 to 20, It must be:

def add(number):
    number  = 1
    return number

for i in range(20):
    print(add(i))
  •  Tags:  
  • Related