Table of Contents
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 the following Python programming topics:
1. 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...elif...else statement. We can do the same thing using nested if statements as follows.
2. 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 the 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.
Related posts:
How to get current date and time in Python?
Python Program to Find Armstrong Number in an Interval
Python memoryview()
Python Program to Differentiate Between type() and isinstance()
Python Iterators
Python String expandtabs()
Python Program to Print Output Without a Newline
Python property()
Python File I/O Operation
Python List insert()
Python Exception Handling Using try, except and finally statement
Python Program to Count the Number of Occurrence of a Character in String
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python del Statement
Python Errors and Built-in Exceptions
Python String translate()
Python List Comprehension
Python Program Read a File Line by Line Into a List
Python Program to Find the Sum of Natural Numbers
Python format()
Python Program to Convert Celsius To Fahrenheit
Python String rjust()
Python Program to Multiply Two Matrices
Python ord()
Python Program to Remove Punctuations From a String
Python classmethod()
Python String lstrip()
Python Program to Randomly Select an Element From the List
Python Program to Differentiate Between del, remove, and pop on a List
Python all()
Python Dictionary keys()
Python filter()