×

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

Attributes in python

In this article, we shall learn about attributes in python. Classes are a mix of data and functions, which in reality mean attributes and methods respectively. Typically, the body of a...

3 minutes read.

Python History

Python is one of the top trending, widely-used programming languages. Python is a general-purpose programming language. Python language is known for its features. Some features are given below: SimplisticFree and open...

4 minutes read.

How to handle exceptions in python

Prerequisite: Exceptions and errors in Python What are Exceptions? Exceptions are run-time errors that unexpectedly occur and crash a program. When occurred, it alters the flow of the program. These errors are...

9 minutes read.

Python Assert

Python Assert Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an...

2 minutes read.

__init__ in python

Every programmer will enclose to object-oriented programming (OOP) these days. As we know, that python is the latest and most modern programming language; python supports to implementation of object-oriented philosophy....

5 minutes read.

Python datetime

Python provides a module named datetime to work with the date and time. Sometimes in the real life application development, we need to work with the date and time. The date is...

3 minutes read.

Difference between Python 2 and Python 3

In this tutorial, we will learn the differences between two versions of python, that is, python version 2 and python version 3. Some basic differences include- Python 2 is the older version...

3 minutes read.

Python Array

Python Array In the programming language or computer science, an array is defined as the form of a data structure which consists of or store collection of various types of elements...

10 minutes read.

Python variance() function

Variance The variance is the average of the square deviations from the mean. The variance will measure the spread of the dataset from its mean or median value. The greater the...

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.

Check if a String is Empty in Python

The string is one of the data types of Python. This data type stores all kinds of data but all the characters must be enclosed using double quotes (""). In...

5 minutes read.

How to Install PIP In Python

How to Install PIP In Python The libraries for Python have made our work easier than we expected. From a simple addition of two numbers to applying algorithms on the big...

4 minutes read.

String indices must be integers in Python

Lists, tuples, and strings are examples of iterable objects in Python whose items or characters can be retrieved by their index numbers. For instance, you might take the following action to...

3 minutes read.

Python lock

Before understanding the concept of Python-lock we need to understand what kind if condition we require to implement the locks in Python. Let us start with multithreading and its implementation...

5 minutes read.

Python Selectors

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

4 minutes read.

List in Python

What is List in Python In Python, lists are used to store the multiple values in one variable. We can say that list is the collection of similar as well as...

3 minutes read.

Nested Tuple in Python

If you are a Python learner, this page contains all the information that helps you know about nested tuple and how to access it in python. What is a Tuple? Multiple items...

4 minutes read.

Python Super function

The super function is used to access and call the methods or functions involved in the parent class during Inheritance. What is Inheritance? The process where the parent class inherits some of...

3 minutes read.

Python Indentation

Overview The spaces at the start of a code line are known as an indentation in Python programming. Indentation is only used for readability in other programming languages like C, C++,...

8 minutes read.

Python Goto Statement

We all know that Python is the most basic and widely used programming language in the world. It is also one of the world's most popular and widely used languages....

4 minutes read.