Performing recursion but the code is running twice

Viewed 50

I am trying to perform recursion but the code is running twice. How to break recursion loop? I want it to run only once. Can anyone help me out with this?

x = 5
def my_fun():
    global x

    if x == 5:
        print('x is 5')
        x = 3
        my_fun()

    print('x is 3')

my_fun()

Expected Output

  • x is 5
  • x is 3

Output from code

  • x is 5
  • x is 3
  • x is 3
4 Answers

Why are you using recursion for this? But ok. Anyway, using parameters is a better way to do it than global.

def my_fun(x):
    if x >= 3:
        print(x)
        x-=2
        my_fun(x)

my_fun(5)

you need to use else in my_func when x!=5 to get the expected output

>>> x= 5
>>> def func():
...     global x
...     if x ==5:
...             print('x is 5')
...             x = 3
...             func()
...     else:
...             print('x is 3')
... 
>>> func()
x is 5
x is 3

def my_fun():
    global x
    if x == 5:
        print('x is 5')
        x = 3
        my_fun()
    else:
        print('x is 3')

my_fun()

On your initial call, x = 5 and "x is 5" is printed. x is changed to 3.

Then the function calls itself.

The if clause is false, so only "x is 3" is printed.

The recursion returns and the initial call is continued. "x is 3" is printed.

Related