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 Randomly Select an Element From the List
Python sorted()
Python Program to Check Whether a String is Palindrome or Not
Python reversed()
Python Function Arguments
Python Program to Check Armstrong Number
Python String index()
Python complex()
Python Tuple count()
Python Deep Learning Cookbook - Indra den Bakker
Python String isnumeric()
Python String isdecimal()
Python while Loop
Python Get Current time
Python Numbers, Type Conversion and Mathematics
Python Dictionary items()
Python List copy()
Python String lower()
Deep Learning with Python - Francois Chollet
Python Global, Local and Nonlocal variables
Python Operators
Python Objects and Classes
Python Closures
Python bytearray()
Node.js vs Python for Backend Development
Python Program to Get File Creation and Modification Date
Python Program to Transpose a Matrix
Python String title()
Python Data Structures and Algorithms - Benjamin Baka
Python slice()
Deep Learning with Python - Francois Cholletf
Python Program to Extract Extension From the File Name