Home > Mobile >  How to change the variable value defined with 'outer' function definition through implemen
How to change the variable value defined with 'outer' function definition through implemen

Time:06-05

I'm trying to writing some codes that defines the outer function including inner function.

def outer():

  t = 1
  
  for i in range(3):

    print(f'## {i}th loop##')
    
    t = inner(t)

  return t

def inner(t):
  print(f't value is now {t}')

  t  = 1
  if (t % 10) != 0: # imaginary if-condition to reproduce my original codes
    inner(t)

  return t

outer()

While doing this, I confronted the problem that implementing inner function few times does not change the variable value that was defined with the definition of outer function at the same time.

The result of codes above is:

The result

In first iter, t : 1,2,3,4,5,6,7,8,9
In second iter, t : 2,3,4,5,6,7,8,9 ..

I expected that the t value in the second iteration will start with the value of 10. Would u let me know what the problem is?

CodePudding user response:

The problem is how you are calling:

outer -> inner -> inner -> last inner, etc.

Resulting in t = 1 at the end, from the last inner call.

If you want to get it functional, and still use inner and outer you can do this:

def outer():
    t = 0

    for i in range(3):
        print(f'## {i}th loop##')

        t = inner(t)


def inner(num):

    for j in range(num, num   10):
        print(f't value is now {j}')
        num  = 1

    return num


outer()

CodePudding user response:

This issue is in line:

inner(t)

Changes in the recursive calls has no effect on the parent--see How do I pass a variable by reference?.

This can be fixed by changing to:

t = inner(t)

Codes becomes:

def outer():

  t = 1
  
  for i in range(3):

    print(f'## {i}th loop##')
    
    t = inner(t)

  return t

def inner(t):
  print(f't value is now {t}')

  t  = 1       # equivalent to t = t   1 
               # which creates a new local value of t and assigns it to passed in argument t   1
    
  if (t % 10) != 0: # imaginary if-condition to reproduce my original codes
    t = inner(t)       

  return t

outer()

Output

## 0th loop##
t value is now 1
t value is now 2
t value is now 3
t value is now 4
t value is now 5
t value is now 6
t value is now 7
t value is now 8
t value is now 9
## 1th loop##
t value is now 10
t value is now 11
t value is now 12
t value is now 13
t value is now 14
t value is now 15
t value is now 16
t value is now 17
t value is now 18
t value is now 19
## 2th loop##
t value is now 20
t value is now 21
t value is now 22
t value is now 23
t value is now 24
t value is now 25
t value is now 26
t value is now 27
t value is now 28
t value is now 29
  • Related