Checking if a Number is Positive, Negative, or Zero Using if...elif...else
The following example demonstrates how to use the if...elif...else statement in Python to determine if a number is positive, negative, or zero.
Example 1: Using if...elif...else
# User inputs a number
num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")Output:
Enter a number: 3 Positive number
In this example, the program prompts the user to input a number and then evaluates whether the number is positive, zero, or negative using the if...elif...else structure.
Using Nested if Statements
We can also achieve the same result by using a nested if statement inside another if statement, as shown below.
Example 2: Using Nested if Statements
# Nested if statement
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")Output:
Enter a number: 0 Zero
In this version, the program first checks if the number is greater than or equal to zero. If the number is equal to zero, it prints "Zero"; otherwise, it prints "Positive number". If the number is less than zero, it prints "Negative number".