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 String capitalize()
Python String translate()
Python Program to Create Pyramid Patterns
Python String isidentifier()
Python String find()
Python iter()
Python Dictionary clear()
Python Program to Print Output Without a Newline
Python enumerate()
Python List pop()
Python Set clear()
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python String maketrans()
Python Program to Display Fibonacci Sequence Using Recursion
Python String count()
Python Dictionary get()
Python getattr()
Python Tuple count()
Python staticmethod()
Python del Statement
Python String isdecimal()
Python compile()
Python next()
Python Dictionary items()
Python Program to Find Sum of Natural Numbers Using Recursion
Python String rsplit()
Python Set symmetric_difference_update()
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python divmod()
Python Program to Get Line Count of a File
Python Program to Find HCF or GCD
Python Data Structures and Algorithms - Benjamin Baka