×

Python If-else statement

In real life, there are situations where we have to make decisions for a particular circumstance and based on those decisions, and we plan our next move. The same thing happens while writing a code. Whenever we write a code in any programming language, some situations or conditions will arise where we have to decide, and that decision greatly impacts the program’s output. Decision-making is a very important part of our life and is equally important in a programming language.  Decision-making helps to write an efficient code. In programming languages, decision-making helps in deciding the flow of the code.

In any programming language, if-else keywords are used for decision-making. If-else statements are used for deciding the flow of the code.

Python if-statement

If statements are the basic block of decision-making. Now any code written inside an if statement will only run if the condition or the test expression written along with it will be true. All if statement contains a condition along with it and only when that condition will be true then if statement will run.

The code will not get executed if the condition or the test expression is false.

The code inside the if-statement will be identified based on indentation.

Syntax

# This is the basic syntax for the if statement
if condition:
       statement 1
       statement 2

Example1

if 4 < 5 :
       print(“4 is smaller than 5”) 

Output

4 is smaller than 5

Explanation

In the above code, if statements are written using the if-keyword, we have a condition: if 4 is less than 5 or not. Since the condition is true, only then we would be able to enter inside the conditional statement.

Example2

if 4 < 5:
print(“4 is less than 5”) 

Output

print(“4 is less than 5”) 
  ^
IndentationError

Explanation

In the above code, we can see code will throw an error while executing. This error occurred because the indentation is wrong in the given code. In python, it is very important to follow the indentation; otherwise, it will throw an indentation error. In python, we use four whitespaces to provide indentation. But we can also give at least one whitespace to provide indentation.

We can also use any numeric value instead of a condition in a python statement. Any non-zero numeric value is treated as True in python, whereas zero and None are treated as False.

Example3

if 5:
    print(“Welcome to”)
print(“Tutorials And Examples ”)

Output

Welcome to
Tutorials And Example

Explanation

In the above code, instead of a condition, we have used a non-zero value considered true. Hence we were able to print the statement written inside the if-block.

Example4

If 0:
    print(“Welcome to”)
print(“Tutorials And Examples ”)

Output

Tutorials And Example

Explanation

In the above code, we have used zero instead of a condition, which is considered false. Hence the code inside the if statement won’t get executed.

Python else-statement

The else statement is always used with an if-statement. It is like another roadway for the codes.  Else statement will always get executed if no other statement or condition gets executed. Else statement will only work when the if-statement condition is false.

Let’s understand with an example.

Example

# This code will explain the difference between the if-else statement 
x = 20
if x < 10:
       print (“Condition True”)
else:
       print (“Condition False”)

Output

Condition False

Explanation

In the above code, the x is assigned a value of 20. The if-statement condition is if x is less than 10, which is false. Hence code inside the if-block won’t get executed. Then the control will go to the else statement and execute whatever is written inside it.

Python elif-statement

Along with the if-else statement, we also have the elif-statement, which implies ‘if the previous condition is false, then try this condition’. A program can have any number of elif-statement.

Let’s understand with an example.

Example

# This example is for elif-statement
x = 20
y = 20
if x > y:
    print(“x is greater than y”)
elif x == y:
    print(“x is equal to y”)

Output

X is equal to y

Explanation

In the above example, the condition in the if-statement is that ‘x is greater than y’, which is false; hence the code written inside it did not get executed. After that, the machine checks the condition inside the elif-statement: ‘ x is equal to y’, and that is true. So the print statement written inside the elif-statement gets printed.

Let’s us understand the concept with an example.

#This is an overall example including all three statement.

#This is an overall example including all three statement.
i = 100
if (i == 10):
    print("i is 10")
elif (i == 50):
    print("i is 15")
elif (i == 100):
    print("i is 20")
else:
    print("i is not present")

Output

i is 100

Explanation

In the above code, we have assigned i a value of 100. After that, there is an if-statement with the condition ‘ i is equal to 10 ’, which is false. After that, there is an elif-statement with the condition ‘i is equal to 50’, which is also false. After that, there is another elif-statement with the condition ‘i is equal to 100’, which is true. Hence, the control goes inside that elif block and prints the value written inside it.


Related Topics

Reverse a Number in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

4 minutes read.

How to Install Python In Windows

How To Install Python In Windows? Python is a language that every aspirant developer looks forward to. One thing we must keep in our mind is how to begin our hands-on...

3 minutes read.

Python hasattr() function

Python hasattr() function The hasattr() function in Python returns a Boolean value ‘True’ if the given object has the specified attribute, else it returns False. Syntax hasattr(object, name) Parameter object: it is a required parameter which represents an object. attribute:...

1 minute read.

Compound Interest GUI Calculator using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

6 minutes read.

Removing the First Character from the String in Python

String The string is the collection of characters. The strings in python are “immutable”; we cannot change a string once they are created. In python, whatever data we take as input...

4 minutes read.

Python Console

Console in Python is referred as the command line Interpreter- (CLI) and also knows as Shell and it functions as taking input from the human user and interpreting it through...

6 minutes read.

Python program to count the number of a substring in a string

Python program to count the number of a substring in a string A part of the string is called a substring. This article explains the Python program to find how many...

1 minute read.

Python Dictionary copy() method

Python Dictionary copy() method The dictionary.copy () method in Python returns a copy of the specified dictionary. Syntax dictionary.copy () Parameter NA Return None Example 1 # Python program explaining # the dictionary.copy() method # initialising the dictionary ...

1 minute read.

SKLearn Model Selection

The model selections of SK learn has many functions with which we can work on.It has functions to cross-validate the model and, it also provides validation and learning curves.It is...

3 minutes read.

OSError in Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

4 minutes read.

Python Uses

Python has advanced in recent years to rank among the programming languages that are most often used globally. It is utilized in everything, including machine learning, software testing, and website...

4 minutes read.

First Unique Character in a String Python

This article aims to introduce you to strings and how to create a string in Python, and then we will solve a simple yet exciting DSA (Data Structures and Algorithms)...

3 minutes read.

NSE Tools In Python

About NSE NSE (National Stock Exchange) of India Limited is the advanced stock exchange of India. It is located in Mumbai, Maharastra and It was organized in 1992. It was...

2 minutes read.

Python Fit Transform

In machine learning, fit (), transform(), fit transform () methods are provided by scikit learn package. This package is used in model fitting and data processing. These methods are implemented...

2 minutes read.

To Do GUI Application using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Python sum() function

Python sum() function The sum() function in python sums start and the items of an iterable from left to right and returns the total.  Syntax sum(iterable[, start]) Parameter iterable: This parameter represents the sequence to sum. start: It is optional...

1 minute read.

Isodate Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Convert Float to Int in Python using Pandas

Introduction To play with huge amounts of data, in python we require a tool. The tool which is available in Python is pandas. A panda is an open-source library. It is...

4 minutes read.

Best books for NLP with Python

NLP NLP – Natural language processing Computers were created to make the life of mankind easier. But computers cannot understand human language. Instead, they interact with numbers to perform the tasks allotted...

12 minutes read.

Python Dictionary update() method

Python Dictionary update() method The dictionary.update() method in Python inserts the specified items to the dictionary. Syntax dictionary.update(iterable) Parameter iterable- This parameter represents a dictionary or an iterable object with key value pairs, that will...

1 minute read.