用于检查数字是否为正、负、奇、偶、零的程序

先决条件: Python中的循环

null

检查一个数字是正、负、奇、偶还是零。使用if…elif…else和嵌套的if…else语句可以解决这个问题。 方法:

  • 如果一个数字大于零,它就是正的。我们在if表达式中检查这个。
  • 如果为假,则数字将为零或负数。
  • 在随后的表达式中也测试了这一点。
  • 在奇数和偶数的情况下,如果一个数完全可以被2整除,那么它就是偶数。
    • 当数字除以2时,我们使用余数运算符%来计算余数。
    • 如果余数不为零,则数字为奇数。

例如:

Input : 10
Output :
Positive number
10 is Even
Input : 0
Output : 0 is Even

# Python Code to check if a number is
# Positive, Negative, Odd, Even, Zero
# Using if...elif...else
num = 10
if num > 0 :
print ( "Positive number" )
elif num = = 0 :
print ( "Zero" )
else :
print ( "Negative number" )
# Checking for odd and even
if (num % 2 ) = = 0 :
print ( "{0} is Even" . format (num))
else :
print ( "{0} is Odd" . format (num))


Output:
Positive number
10 is Even

# Python Code to check if a number is
# Positive, Negative, Odd, Even, Zero
# Using Nested if
num = 20
if num > = 0 :
if num = = 0 :
print ( "Zero" )
else :
print ( "Positive number" )
else :
print ( "Negative number" )
# Cchecking for odd and even
if (num % 2 ) = = 0 :
print ( "{0} is Even" . format (num))
else :
print ( "{0} is Odd" . format (num))


Output:
Positive number
20 is Even
© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享