Home > Enterprise >  Performing recursion but the code is running twice
Performing recursion but the code is running twice

Time:07-16

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

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

Why do you expected print(x is 3) run one-time. If you want to get print('x is 3') only one-time, you can set return after calling my_fun().

x = 5
def my_fun():
    global x

    if x == 5:
        print('x is 5')
        x = 3
        my_fun() # -> call my_fun()
        # after call and end we return here
        # You can see print('x is 3') one-time with set return
        # return
    # we see below line two-time, first from first call, second from second call
    print('x is 3') 

my_fun()

If you want to get a recursion function you can try like below.

def my_fun(x):
    print(f'x is {x}')
    if x == 5:
        x = 3
        my_fun(x)

my_fun(5)

x is 5
x is 3

CodePudding user response:

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

my_fun()

CodePudding user response:

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