📌  相关文章
📜  检查一个数字是正数、负数、奇数、偶数、零的程序

📅  最后修改于: 2022-05-13 01:55:13.384000             🧑  作者: Mango

检查一个数字是正数、负数、奇数、偶数、零的程序

先决条件: Python中的循环

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

  • 如果一个数大于零,则该数为正数。我们在 if 的表达式中检查这一点。
  • 如果为 False,则该数字将为零或负数。
  • 这也在随后的表达式中进行了测试。
  • 在奇偶的情况下,一个数是偶数,即使它可以被 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