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 List copy()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python String rsplit()
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Program to Merge Mails
Python Program to Represent enum
Python Program to Find LCM
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python Program to Trim Whitespace From a String
Python String capitalize()
Python Program to Check If Two Strings are Anagram
Python ord()
Python Program to Check Prime Number
Python repr()
Python Program to Find Armstrong Number in an Interval
Python String islower()
Python Variables, Constants and Literals
Python Program to Sort Words in Alphabetic Order
Python Program to Iterate Through Two Lists in Parallel
Python Closures
Python dir()
Python Set intersection()
Python String rstrip()
Python Program to Make a Flattened List from Nested List
Python frozenset()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python Program to Merge Two Dictionaries
Python Program to Access Index of a List Using for Loop
Python Object Oriented Programming
Python Directory and Files Management
Python min()
Node.js vs Python for Backend Development