递归确定给定数是偶数还是奇数的Python程序
在本文中,我们将看到如何编写程序以使用递归方法查找给定数字是偶数还是奇数。如果该数字甚至在Python中返回 true else false 。
为此,我们使用 Operator Called 模运算符。当我们需要计算该数除以任何除数时的余数时,该运算符用于运算。
- 偶数:能被2整除的数,所以余数为0
- 奇数:不能被2整除的数,所以余数是1
例子:
Input: 2
Output: True
Explanation : 2 % 2==0 So True
Input: 5
Output: False
Expalantion : 2 % 2 != 0 So, False
方法#1:
方法 :
- 我们使用通过将数字减去数字 2 来获得余数而不使用模运算符的概念
- 如果最后,我们得到任何余数,则该数字为奇数并返回该数字的 False
- 否则数字是偶数并为该数字返回 True
Python3
# defining the function having the one parameter as input
def evenOdd(n):
#if remainder is 0 then num is even
if(n==0):
return True
#if remainder is 1 then num is odd
elif(n==1):
return False
else:
return evenOdd(n-2)
# Input by geeks
num=3
if(evenOdd(num)):
print(num,"num is even")
else:
print(num,"num is odd")
Python3
# defining the function having
# the one parameter as input
def evenOdd(n):
#if remainder is 0 then num is even
if(n % 2 == 0):
return True
#if remainder is 1 then num is odd
elif(n %2 != 0):
return False
else:
return evenOdd(n)
# Input by geeks
num = 3
if(evenOdd( num )):
print(num ,"num is even")
else:
print(num ,"num is odd")
Python3
# writing the function having the range
# and printing the even in that range
def evenOdd(a,b):
if(a>b):
return
print(a ,end=" ")
return evenOdd(a+2,b)
# input by geeks
x=2
y=10
if(x % 2 ==0):
x=x
else:
# if the number x is odd then
# add 1 the number into it to
# avoid any error to make it even
x+=1
evenOdd(x,y)
输出:
3 num is odd
方法#2:
我们使用模运算符来找到偶数或奇数 就像 if num % 2 == 0 那么余数是 0 所以给定的数字是偶数并返回 True
否则,如果 num % 2 != 0 则余数不为零,因此给定的数字为奇数并返回 False
蟒蛇3
# defining the function having
# the one parameter as input
def evenOdd(n):
#if remainder is 0 then num is even
if(n % 2 == 0):
return True
#if remainder is 1 then num is odd
elif(n %2 != 0):
return False
else:
return evenOdd(n)
# Input by geeks
num = 3
if(evenOdd( num )):
print(num ,"num is even")
else:
print(num ,"num is odd")
输出:
3 num is odd
方法 #3:打印范围 (a, b) 的所有偶数
这里我们将在函数evenOdd(n) 中打印给定范围 n 的所有偶数
蟒蛇3
# writing the function having the range
# and printing the even in that range
def evenOdd(a,b):
if(a>b):
return
print(a ,end=" ")
return evenOdd(a+2,b)
# input by geeks
x=2
y=10
if(x % 2 ==0):
x=x
else:
# if the number x is odd then
# add 1 the number into it to
# avoid any error to make it even
x+=1
evenOdd(x,y)
输出:
2 4 6 8 10