Python Program to Check if a Number is Positive, Negative or 0

P

In this example, you will learn to check whether a number entered by the user is positive, negative or zero. This problem is solved using if…elif…else and nested if…else statement.

To understand this example, you should have the knowledge of following Python programming topics:

  1. WHAT IS PYTHON? THINGS TO KNOW BEFORE CODE WITH PYTHON
  2. HOW DO I GET AND INSTALL PYTHON?
  3. PYTHON PRIMITIVES – VARIABLES, BUILT-IN DATA TYPES, COMMENTS, SYNTAX, AND SEMANTICS
  4. CODING APPROACHES IN PYTHON
  5. STYLE GUIDE FOR PROGRAMMING PYTHON CODE
  6. ERRORS AND EXCEPTIONS IN PYTHON

Source Code: Using if…elif…else

num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

Here, we have used the if…elseif…else statement. We can do the same thing using nested if statements as follows.

Source Code: Using Nested if

num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
The output of both programs will be same.

Output 1

Enter a number: 2
Positive number

Output 2

Enter a number: 0
Zero

A number is positive if it is greater than zero. We check this in the expression of if. If it is False, the number will either be zero or negative. This is also tested in subsequent expression.

About the author

Pardeep Patel
Pardeep Patel

Add comment

Basics of Python