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 frozenset()
Python Program to Randomly Select an Element From the List
Python complex()
Python min()
Python Program to Find Factorial of Number Using Recursion
Python Program to Check if a Number is Odd or Even
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python List insert()
Python String istitle()
Python Program to Return Multiple Values From a Function
Python Operator Overloading
Python sorted()
Python List copy()
Python timestamp to datetime and vice-versa
Python list()
Python datetime
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Program to Access Index of a List Using for Loop
Python String expandtabs()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python Program to Swap Two Variables
Python help()
Python Errors and Built-in Exceptions
Python Program to Remove Duplicate Element From a List
Python Program to Remove Punctuations From a String
Python Matrices and NumPy Arrays
Python bytes()
Python Program to Measure the Elapsed Time in Python
Python Set clear()
Python Program to Find the Largest Among Three Numbers
Python String format()