Python3 – if , if..else, Nested if, if-elif statements

Last Updated : 09 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

There are situations in real life when we need to do some specific task and based on some specific conditions, we decide what we should do next. Similarly, there comes a situation in programming where a specific task is to be performed if a specific condition is True. In such cases, conditional statements can be used. The following are the conditional statements provided by Python. 

  1. if
  2. if..else
  3. Nested if
  4. if-elif statements.

Let us go through all of them. 

if Statement in Python

If the simple code of block is to be performed if the condition holds true then the if statement is used. Here the condition mentioned holds then the code of the block runs otherwise not.

Python if Statement Syntax

Syntax: if condition:

# Statements to execute if

# condition is true

Flowchart of if Statement in Python

Below is the flowchart by which we can understand how to use if statement in Python:

if-statement-in-Python

Example: Basic Conditional Check with if Statement

In this example, an if statement checks if 10 is greater than 5. If true, it prints “10 greater than 5”; regardless, it then prints “Program ended” as the next statement, indicating the program flow.

Python
# if statement example
if 10 > 5:
    print("10 greater than 5")

print("Program ended")

Output
10 greater than 5
Program ended


Indentation(White space) is used to delimit the block of code. As shown in the above example it is mandatory to use indentation in Python3 coding.

if else Statement in Python

In conditional if Statement the additional block of code is merged as else statement which is performed when if condition is false. 

Python if-else Statement Syntax  

Syntax: if (condition): # Executes this block if # condition is trueelse: # Executes this block if # condition is false

Flow Chart of if-else Statement in Python

Below is the flowchart by which we can understand how to use if-else statement in Python:

if-else-statement-in-Python

Example 1: Handling Conditional Scenarios with if-else

In this example, the code assigns the value 3 to variable x and uses an if..else statement to check if x is equal to 4. If true, it prints “Yes”; otherwise, it prints “No,” demonstrating a conditional branching structure.

Python
# if..else statement example
x = 3
if x == 4:
    print("Yes")
else:
    print("No")

Output
No


Example 2: Nested if..else Chain for Multiple Conditions

You can also chain if..else statement with more than one condition. In this example, the code uses a nested if..else chain to check the value of the variable letter. It prints a corresponding message based on whether letter is “B,” “C,” “A,” or none of the specified values, illustrating a hierarchical conditional structure.

Python
# if..else chain statement
letter = "A"

if letter == "B":
    print("letter is B")

else:

    if letter == "C":
        print("letter is C")

    else:

        if letter == "A":
            print("letter is A")

        else:
            print("letter isn't A, B and C")

Output
letter is A


Nested if Statement

if statement can also be checked inside other if statement. This conditional statement is called a nested if statement. This means that inner if condition will be checked only if outer if condition is true and by this, we can see multiple conditions to be satisfied.

Python Nested If Statement Syntax

Syntax: if (condition1): # Executes when condition1 is true if (condition2): # Executes when condition2 is true # if Block is end here# if Block is end here

Flow chart of Nested If Statement In Python

Below is the flowchart by which we can understand how to use nested if statement in Python:

nested-if-in-Python


Example: Managing Nested Conditions for Refined Control

In this example, the code uses a nested if statement to check if the variable num is greater than 5. If true, it further checks if num is less than or equal to 15, printing “Bigger than 5” and “Between 5 and 15” accordingly, showcasing a hierarchical condition for refined control flow.

Python
# Nested if statement example
num = 10

if num > 5:
    print("Bigger than 5")

    if num <= 15:
        print("Between 5 and 15")

Output
Bigger than 5
Between 5 and 15


if-elif Statement in Python

The if-elif statement is shortcut of if..else chain. While using if-elif statement at the end else block is added which is performed if none of the above if-elif statement is true.

Python if-elif Statement Syntax:-  

Syntax: if (condition): statementelif (condition): statement..else: statement

Flow Chart of Python if-elif Statement

Below is the flowchart by which we can understand how to use elif in Python:

if-else-if-ladder-in-Python

Example: Sequential Evaluation with if-elif-else Structure

In this example, the code uses an if-elif-else statement to evaluate the value of the variable letter. It prints a corresponding message based on whether letter is “B,” “C,” “A,” or none of the specified values, demonstrating a sequential evaluation of conditions for controlled branching.

Python
# if-elif statement example
letter = "A"

if letter == "B":
    print("letter is B")

elif letter == "C":
    print("letter is C")

elif letter == "A":
    print("letter is A")

else:
    print("letter isn't A, B or C")

Output
letter is A



Can We Use Elif in Nested If?

Yes, you can use elif within nested if statements in Python. This allows for more complex decision structures within a branch of another decision. For example:

python
x = 10
y = 5
if x > 5:
if y > 5:
print("x and y are greater than 5")
elif y == 5:
print("x is greater than 5 and y is 5")
else:
print("x is greater than 5 and y is less than 5")

This structure provides conditional checks within another conditional check, enhancing the decision-making capabilities of your code.

Are You Allowed to Nest If Statements Inside Other If Statements in Python?

Yes, you are allowed to nest if statements inside other if statements in Python. This is a common practice used to make more complex conditional logic possible. Nested if statements can be as deep as you need, although deep nesting can make your code harder to read and maintain.

Python3 – if , if..else, Nested if, if-elif statements – FAQs

Can We Use Multiple If Instead of Elif?

Yes, you can use multiple if statements instead of elif, but the behavior of your code will change. elif allows for mutually exclusive conditions; only one branch can execute. With multiple if statements, each if condition is checked independently of others, so multiple branches might execute.

Example:

x = 10
y = 5
if x > 5:
if y > 5:
print("x and y are greater than 5")
elif y == 5:
print("x is greater than 5 and y is 5")
else:
print("x is greater than 5 and y is less than 5")

Using elif, the second condition would only be checked if the first condition failed.

What is the Difference Between if-else and Nested If Statements in Python?

  • if-else: Refers to a simple conditional structure where if a condition is true, the if block executes; otherwise, the else block executes. There is only one alternative path.
  • Nested if statements: Involve placing one or more if or if-else structures inside another if or else block. This setup is used to test for further conditions after a previous condition has been found to be true.

What is the Maximum Number of Elif Clauses You Can Have in a Conditional?

Python does not explicitly limit the number of elif clauses you can have after an if statement. The practical limit is generally dictated by the readability and complexity of your code. Technically, you could have hundreds or even thousands, but this would be poor practice in terms of code clarity and maintainability. If you find yourself using many elif statements, consider refactoring your code, possibly using a different data structure like a dictionary to map conditions to functions or outcomes, or using a different logic flow altogether.



Similar Reads

Avoiding elif and ELSE IF Ladder and Stairs Problem
This article focuses on discussing the elif and else if ladder and stairs problem and the solution for the same in the C and Python Programming languages. The ELIF and ELSE IF Ladder and Stairs ProblemThere are programmers who shy away from long sequences of IF, ELSE IF, ELSE IF, ELSE IF , etc. typically ending with a final ELSE clause. In language
6 min read
How to use if, else &amp; elif in Python Lambda Functions
Lambda function can have multiple parameters but have only one expression. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to use if, else &amp; elif in Lambda Functions. Using if-else in lambda functionThe lambda function will return a value for every validat
2 min read
Python If Else Statements - Conditional Statements
In both real life and programming, decision-making is crucial. We often face situations where we need to make choices, and based on those choices, we determine our next actions. Similarly, in programming, we encounter scenarios where we must make decisions to control the flow of our code. Conditional statements in Python play a key role in determin
8 min read
Arcade inbuilt functions to draw polygon in Python3
The arcade library is a high-tech Python Package with advanced set of tools for making 2D games with gripping graphics and sound. It is Object-oriented and is especially built for Python 3.6 and above versions. Arcade has two inbuilt functions for drawing a polygon: 1. arcade.draw_polygon_outline( ) : This function is used to draw the outline of th
2 min read
How to write Comments in Python3?
Comments are text notes added to the program to provide explanatory information about the source code. They are used in a programming language to document the program and remind programmers of what tricky things they just did with the code and also help the later generation for understanding and maintenance of code. The compiler considers these as
4 min read
How to show a timer on screen using arcade in Python3?
Prerequisite: Arcade library Arcade is a modern framework, which is used to make 2D video games. In this, article, you will learn how to show an on-screen timer using the arcade module of Python. Displaying a timer on screen is not tough job, just follow the below steps:- Step 1: First of all import the arcade module of Python C/C++ Code Step 2: De
2 min read
Python2 vs Python3 | Syntax and performance Comparison
Python 2.x has been the most popular version for over a decade and a half. But now more and more people are switching to Python 3.x. Python3 is a lot better than Python2 and comes with many additional features. Also, Python 2.x is becoming obsolete this year. So, it is now recommended to start using Python 3.x from now-onwards. Still in dilemma? Ev
4 min read
How to install Python3 and PIP on Godaddy Server?
GoDaddy VPS is a shared server that provides computational services, databases, storage space, automated weekly backups, 99% uptime, and much more. It’s a cheaper alternative to some other popular cloud-based services such as AWS, GPC, and Azure. Python is an open-source, cross-platform, high-level, general-purpose programming language created by G
2 min read
Automate the Conversion from Python2 to Python3
We can convert Python2 scripts to Python3 scripts by using 2to3 module. It changes Python2 syntax to Python3 syntax. We can change all the files in a particular folder from python2 to python3. Installation This module does not come built-in with Python. To install this type the below command in the terminal. pip install 2to3 Syntax: 2to3 [file or f
1 min read
Convert String to Double in Python3
Given a string and our task is to convert it in double. Since double datatype allows a number to have non -integer values. So conversion of string to double is the same as the conversion of string to float This can be implemented in these two ways 1) Using float() method C/C++ Code str1 = &quot;9.02&quot; print(&quot;This is the initial string:
2 min read
Introduction to Python3
Python is a high-level general-purpose programming language. Python programs generally are smaller than other programming languages like Java. Programmers have to type relatively less and indentation requirements of the language make them readable all the time. Note: For more information, refer to Python Programming Language Learn Python 3 from beg
3 min read
Why PyPy3 is preferred over Python3?
"If you want your code to run faster, you should probably just use PyPy." -- Guido van Rossum (creator of Python) If you have ever coded in Python, you know how much slower it is compared to some of the other popular programming languages. In most of the online code judges, the time limit of Python is as much a 5 times more than that of C and more
3 min read
How to Install Python3 on AWS EC2?
AWS or Amazon web services is a cloud service platform that provides on-demand computational services, databases, storage space, and many more services. EC2 or Elastic Compute Cloud is a scalable computing service launched on the AWS cloud platform. In simpler words, EC2 is nothing but a virtual computer on which we can perform all our tasks and we
3 min read
Different Input and Output Techniques in Python3
An article describing basic Input and output techniques that we use while coding in python. Input Techniques 1. Taking input using input() function -&gt; this function by default takes string as input. Example: C/C++ Code #For string str = input() # For integers n = int(input()) # For floating or decimal numbers n = float(input()) 2. Taking Multipl
3 min read
New '=' Operator in Python3.8 f-string
Python have introduced the new = operator in f-string for self documenting the strings in Python 3.8.2 version. Now with the help of this expression we can specify names in the string to get the exact value in the strings despite the position of the variable. Now f-string can be defined as f'{expr=}' expression. We can specify any required name in
1 min read
Positional-only Parameter in Python3.8
Python introduces the new function syntax in Python3.8.2 Version, Where we can introduce the / forward slash to compare the positional only parameter which comes before the / slash and parameters that comes after * is keyword only arguments. Rest of the arguments that are come between / and * can be either positional or keyword type of argument. Th
2 min read
Itertools in Python3
Itertools is a module in Python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Why to use ? This module incorporates functions that
3 min read
Setting python3 as Default in Linux
Python 2 support ended on 1-January-2020, and many major projects already signed the Python 3 Statement that declares that they will remove Python 2 support. However many of us prefer to code on python interpreter for tiny code snippets, instead of making .py files. And when we fire command 'python' on the terminal, interpreter of python2 gets laun
1 min read
Python3 Program to Count of rotations required to generate a sorted array
Given an array arr[], the task is to find the number of rotations required to convert the given array to sorted form.Examples: Input: arr[] = {4, 5, 1, 2, 3} Output: 2 Explanation: Sorted array {1, 2, 3, 4, 5} after 2 anti-clockwise rotations. Input: arr[] = {2, 1, 2, 2, 2} Output: 1 Explanation: Sorted array {1, 2, 2, 2, 2} after 1 anti-clockwise
4 min read
How to print spaces in Python3?
In this article, we will learn about how to print space or multiple spaces in the Python programming language. Spacing in Python language is quite simple than other programming language. In C languages, to print 10 spaces a loop is used while in python no loop is used to print number of spaces. Following are the example of the print spaces: Example
2 min read
How to use Variables in Python3?
Variable is a name for a location in memory. It can be used to hold a value and reference that stored value within a computer program. the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to the variables, you can store integers, strings, decimals, complex in these vari
3 min read
What is Three dots(...) or Ellipsis in Python3
Ellipsis is a Python Object. It has no Methods. It is a singleton Object i.e. , provides easy access to single instances. Various Use Cases of Ellipsis (...): Default Secondary Prompt in Python interpreter.Accessing and slicing multidimensional Arrays/NumPy indexing.In type hinting.Used as Pass Statement inside Functions.Default Secondary Prompt in
3 min read
How to create an instance of a Metaclass that run on both Python2 and Python3?
Metaclasses are classes that generate other classes. It is an efficient tool for class verification, to prevent sub class from inheriting certain class function, and dynamic generation of classes. Here we will discuss how to create an instance of a Metaclass that runs on both Python 2 and Python 3. Before delving into it, let's go through the code
3 min read
Flipping Tiles (memory game) using Python3
Flipping tiles game can be played to test our memory. In this, we have a certain even number of tiles, in which each number/figure has a pair. The tiles are facing downwards, and we have to flip them to see them. In a turn, one flips 2 tiles, if the tiles match then they are removed. If not then they are flipped and placed back in the position. We
3 min read
Making an object jump with gravity using arcade module in Python3
The Arcade library is a modern Python Module used widely for developing 2D video games with compelling graphics and sound. Arcade is an object-oriented library. It can be installed like any other Python Package. Now, it’s up to the necessity of the developer, what type of game, graphics, and sound he/she wants to use using this toolkit. So, in this
4 min read
Arcade inbuilt functions to draw point(s) in Python3
The Arcade library is a modern Python Module used widely for developing 2D video games with compelling graphics and sound. Arcade is an object-oriented library. It can be installed like any other Python Package. In this article, we will learn what are the arcade inbuilt functions to draw point. Arcade library is a modern framework, which makes draw
3 min read
Draw a parabola using Arcade in Python3
Arcade is a Python library which is used for developing 2Dimensional Games. Arcade needs support for OpenGL 3.3+. In arcade, basic drawing does not require knowledge on how to define functions or classes or how to do loops, simply we have inbuilt functions for drawing primitives. Arcade inbuilt function for drawing parabola:- 1. arcade.draw_parabol
3 min read
Draw a circle using Arcade in Python3
The arcade library is a high-tech Python Package with advanced set of tools for making 2D games with gripping graphics and sound. It is Object-oriented and is especially built for Python 3.6 and above versions. Arcade inbuilt functions to draw circle :- 1. arcade.draw_circle_outline( ) : This function is used to draw the outline of a circle. Syntax
3 min read
How to copy file in Python3?
Prerequisites: Shutil When we require a backup of data, we usually make a copy of that file. Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Here we will learn how to copy a file using Python3. Method 1 : Using shutil library shutil libra
2 min read
Python3 Program to Find Maximum value possible by rotating digits of a given number
Given a positive integer N, the task is to find the maximum value among all the rotations of the digits of the integer N. Examples: Input: N = 657Output: 765Explanation: All rotations of 657 are {657, 576, 765}. The maximum value among all these rotations is 765. Input: N = 7092Output: 9270Explanation:All rotations of 7092 are {7092, 2709, 9270, 09
2 min read
Practice Tags :