Home > Mobile >  Recursion output isn't printing
Recursion output isn't printing

Time:11-07

I'm new to python and trying to understand recursion. I'm trying to write a code where someone inputs 2 numbers (Num1, Num2). A calculation will take place until Num1 is greater than Num 2. The result of the calculation's final value should then be outputted.

This is my code:

def Recursive(Num1, Num2):
    if Num1 > Num2:
        return(10)
    else:
        if Num1 == Num2:
            return(Num1)
        else:
            return(Num1 Recursive(Num1 * 2, Num2))

Num1=input("Enter number 1: ")
Num2=input("Enter number 2: ")
print("Final value: ", Recursive(Num1, Num2))

This is the output that comes out:

Enter number 1: 1
Enter number 2: 15

That's it. There's no output of my print statement. I'm confused as to what I'm doing wrong here and what I should do.

CodePudding user response:

def Recursive(Num1, Num2):
    if Num1 > Num2:
        return 10
    if Num1 == Num2:
        return Num1
    print(Num1, Num2)
    return Num1   Recursive(Num1 * 2, Num2)

Num1=int(input("Enter number 1: "))
Num2=int(input("Enter number 2: "))
print("Final value: ", Recursive(Num1, Num2))

This should be working code, the reason why your code was not working was because without the int in Num1 = int( input("") ) the program was reading the number as a string. As a result instead of getting 2 from Num1 * 2 when Num1 is 1 you got 11 as it was multiplying a string instead of an integer.

# Here is an example

a = input("Input a number: ")
b = int(input("input a number: "))

print(f"a is a:{type(a)}\n b is a:{type(b)}")

print(f"{a * 2}\n{b * 2}")

Copy the code above input the two numbers and it should give you a better understanding of what I just said.

  • Related