Python | Check Whether a Given Number is Even or Odd using Recursion

Let us go through all the methods using which we can solve this problem of finding odd and even numbers

Method 1: Using the number – 2 method

def check_even_odd(n):
	if(n==0):
		return True
	
	elif(n==1):
		return False
	else:
		return check_even_odd(n-2)

num = int(input("Enter the number to check whether the number is even or odd:"))
if(check_even_odd(num)):
	print(num," is an even number")
else:
	print(num," is an odd number")

Output

Enter the number to check whether the number is even or odd:256
256  is an even number

Explanation:

Here in this method, we simply first took the input from the user and then passed on that input to a function that checks for even or odd. Inside the function, we used conditionals. We checked if the number 0 then it is even and if it is 1 then it is odd. If none of the above then we subtract 2 from the given number, if after subtracting the output comes 0 or 1 then it automatically satisfies the given conditionals, if not then we again subtract. In this manner, we used recursion (a function called by that function).

Method 2: Using the remainder method

def check_even_odd(n):
	
	if(n % 2 == 0):
		return True
	
	elif(n %2 != 0):
		return False
	else:
		return check_even_odd(n)

num = int(input("Enter the number to check whether the number is even or odd:"))
if(check_even_odd(num)):
	print(num," is an even number (using remainder method)")
else:
	print(num," is an odd number (using remainder method)")

Explanation

Here we used the modulo operator to find the remainder and then used the conditional.

Method 3: Using the binary (&) method

def check_even_odd(n):
	
    if n & 1:
        return False
    else:
        return True

num = int(input("Enter the number to check whether the number is even or odd:"))
if(check_even_odd(num)):
	print(num," is an even number (using binary AND method)")
else:
	print(num," is an odd number (using binary AND method)")

Explanation

In this last method, we used the concept of binary AND. We passed the value in the function and performed the AND operation on n and 1, if that turns out to be true then we will return False and then will simply print that the number is odd. But if the number is even, then it will return True.

To conclude, in this article, we looked at three methods to find even or odd numbers using precision. We encourage you to share other different methods in the comments.

Share:

Author: Ayush Purawr