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:
Python Program to Find the Size (Resolution) of a Image
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python Namespace and Scope
Python Program to Delete an Element From a Dictionary
Python bool()
Python abs()
Python hasattr()
Python Decorators
Python Program to Catch Multiple Exceptions in One Line
Python Shallow Copy and Deep Copy
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Strings
Python zip()
Python Machine Learning Eqution Reference - Sebastian Raschka
Python del Statement
Python Deep Learning Cookbook - Indra den Bakker
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python len()
Python List reverse()
Python str()
Python Program to Get File Creation and Modification Date
Python Program to Find Factorial of Number Using Recursion
Python String isdigit()
Python Package
Python String islower()
Python Program to Return Multiple Values From a Function
Python List Comprehension
Introduction to Scientific Programming with Python - Joakim Sundnes
Python iter()
Python Exception Handling Using try, except and finally statement
Python Program to Display Fibonacci Sequence Using Recursion