Here are three Python program examples to check if a number is positive, negative or 0 using
- Using if-elif-else statements:
- Using a ternary operator:
- Using a lambda function and map
Using if-elif-else statements
- This program below takes user input as a number and uses if-elif-else statements to check if it’s positive, negative, or zero.
- The corresponding message is then printed to the console.
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: 10
Positive number
Enter a number: -2.5
Negative number
Enter a number: 0
Zero
Using a ternary operator
- This program takes user input as a number and uses a ternary operator to check if it’s positive, negative, or zero.
- The corresponding message is then printed to the console.
num = float(input("Enter a number: "))
print("Positive number" if num > 0 else "Zero" if num == 0 else "Negative number")
Output
Enter a number: 5
Positive number
Using a lambda function and map:
- This program takes user input as a number and uses a lambda function with a map to check if it’s positive, negative, or zero.
- The result is then converted to a list and the first element is printed to the console.
num = float(input("Enter a number: "))
print(list(map(lambda x: "Negative number" if x < 0 else "Zero" if x == 0 else "Positive number", [num]))[0])
Output
Enter a number: 15
Positive number