Editor

Python Program to Check if a Number Is Positive, Negative or Zero

Beginner · Basics

Every number is either positive (greater than 0), negative (less than 0) or exactly zero. This program checks which one a number is, using an if, elif and else chain.

Program

positive_negative_zero.py
num = -7.5 # or: num = float(input("Enter a number: "))
if num > 0:
print(num, "is a positive number")
elif num < 0:
print(num, "is a negative number")
else:
print("The number is zero")
Output
-7.5 is a negative number

How it works

  1. if num > 0 checks for a positive number first.
  2. If that is false, elif num < 0 checks for a negative number.
  3. If neither condition is true, the number can only be zero, so the else branch handles it.
  4. Reading the number with float() in the input() version means decimals like -7.5 work as well as whole numbers.

Other ways to write it

Using a nested if

Using a nested if
num = 0
if num >= 0:
if num == 0:
print("The number is zero")
else:
print(num, "is a positive number")
else:
print(num, "is a negative number")
Output
The number is zero

The outer if splits numbers into "0 or more" and "below 0", and the inner if then separates zero from the positive numbers.

Checking a list of numbers

Checking a list of numbers
def sign_of(n):
if n > 0:
return "positive"
elif n < 0:
return "negative"
return "zero"
for n in [12, -3, 0, 4.5, -0.1]:
print(n, "is", sign_of(n))
Output
12 is positive
-3 is negative
0 is zero
4.5 is positive
-0.1 is negative

A function that returns a word can be reused on many numbers inside a loop.

Try it yourself

Extend the program so that for a whole number it also says whether it is even or odd.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises