×

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

Python Program to Generate a Random String

The term "random" refers to a group of information or data that can be accessed in any chronological order. To create random strings, a Python program called random is utilized....

6 minutes 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.

Read numpy array in Python

Numpy is a numerical python that deals with multidimensional arrays mostly used in storing multiple values. Python's core scientific computing package is called NumPy. This Python library provides multidimensional array...

9 minutes read.

Get Bounding Box Co-ordinates Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

Conditional Expressions in Python

In Python conditional expression are sometimes referred to operator called as ternary operator. Not only Python supports ternary operator but many other programming languages supports it. Ternary operator are the...

2 minutes read.

Difference between Mutable and Immutable Objects

Difference between Mutable and Immutable Objects As we all know that Python is an object-oriented programming language. Object-oriented programming approach is based on the objects and the classes’ stores the data...

4 minutes read.

Scrimba python

Scrimba allows you to study whenever and wherever the topics or concepts you want. It also replaces classroom instruction with interactive screencasts, live events, and student-to-student help. Scrimba is an interactive...

3 minutes read.

Find key from value in dictionary python

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

5 minutes read.

Bar Plot in Python

A bar chart or bar graph displays categorical data using rectangular bars with heights or lengths proportionate to the values for the data distributed in the dataset. In a bar...

16 minutes read.

Append key Value to Dictionary in Python

The Python dictionary is one of the built-in data types. Elements of dictionaries are key-value pairs. In Python, there are numerous ways to add dictionaries. Let's examine some of the...

9 minutes read.

Cx_Oracle Python with Example

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...

6 minutes read.

Python Linked List

Linked List Linked lists non-contiguous linear data structure which is made up of nodes and used to store value and a pointer pointing to the next node. It is linked with...

6 minutes read.

Python Unit Test Cheat String

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Magento 2 Site optimization

Magento 2 Site optimization Magento 2 is a CMS, commonly referred to as Intensive efficiency. Improving the speed and reliability of your Magento 2 app helps clients to achieve a better user experience while...

2 minutes read.

How to Print Pattern in Python

How to Print Pattern in Python. Pattern programs are really important for beginners and they are always asked in all the technical interviews. Multiple loops approach is used to print the different...

6 minutes read.

Python tokens and character set

In this tutorial, we will understand what are character sets used in python and what is meant by python tokens and we will further discuss the type of tokens being...

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.

Sklearn linear Model in Python

The most effective and reliable Python machine learning library is Sklearn. Through a Python consistency interface, it offers a variety of effective tools for statistical modeling and machine learning, including...

5 minutes read.

Data Class in Python

Introduction In Python 3.7, the dataclass modules are introduced as a practical tool for creating organized classes designed specifically for data storage. These classes contain specific attributes and capabilities to deal...

6 minutes read.

Python Argmin

Introduction The argmin function is defined as numpy.argmin(). This function returns the index of the minimum value or element from a Numpy array in a specific axis. An array is taken...

3 minutes read.