[go: up one dir, main page]

Open In App

Nested-if statement in Python

Last Updated : 08 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

There comes a situation in real life when we need to make some decisions and based on these decisions, we decide what we should do next. Similar situations arise in programming also where we need to make some decisions and based on these decisions we choose when to execute the next block of code. This is done with the help of a Nested if statement.

Python Nested if Statement

In Python a Nested if statement, we can have an if…elif…else statement inside another if…elif…else statement. This is called nesting in computer programming. Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. This can get confusing, so it must be avoided if we can.

Flow Chart of Nested if Statement

Python nested if

We can use a simple Python if statement inside another if or if…else statement. It can be used to check multiple if statements. In this case, an if condition is present inside another if conditions. We can have multiple if conditions inside an if condition. The inner if condition will only be executed if and only if the outer if condition is True.

Python if Statement

In this example, first we will check if a number is not equal to zero using the if condition. If it returns True, then we will check if the number is positive, that is, the number is greater than 0.

Syntax

if(condition):
{
    // if body
    // Statements to execute if condition is true
}
Python
# Python code to demonstrate the syntax of if statement

gfg = 9

# if statement with true condition
if gfg < 10:
    print(f"{gfg} is less than 10")

# if statement with false condition
if gfg > 20:
    print(f"{gfg} is greater than 20")

Output:

9 is less than 10

Multiple IF Statements in Python

In this example, we will see how we can use multiple if statements nested inside a single if statement to check multiple conditions. We will take the previous example, but this time we will check for two conditions where the number is positive or negative.

Syntax

if (condition1):
    # executes when condition is True
    if (condition2):
        # executes when condition is True
Python
# Python program to demonstrate 
# nested if with multiple if statements

i = -15; 
# condition 1
if i != 0:
    # condition 2
    if i > 0:
        print("Positive")
    # condition 3
    if i < 0:
        print("Negative")

Output:

Negative

Nested if Statement With else Condition

We can also nest an if statement inside and if else statement in Python. In this example, we will first check if the number is not equal to 0. If it returns True, then we will check if the number if Positive or Negative. If the first If condition returns False, its code block will not execute and the else part of the Python if else statement will execute.

Python
i = 0; 

# if condition 1
if i != 0:
    # condition 1
    if i > 0:
        print("Positive")
        
    # condition 2
    if i < 0:
        print("Negative")
else:
    print("Zero")
    

Output:

Zero


Previous Article
Next Article

Similar Reads

How to write an empty function in Python - pass statement?
In C/C++ and Java, we can write empty function as following // An empty function in C/C++/Java void fun() { } In Python, if we write something like following in Python, it would produce compiler error. # Incorrect empty function in Python def fun(): Output : IndentationError: expected an indented block In Python, to write empty functions, we use pa
1 min read
Using Else Conditional Statement With For loop in Python
Using else conditional statement with for loop in python In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while is executed only when the loop is NOT terminated b
2 min read
Statement, Indentation and Comment in Python
Here, we will discuss Statements in Python, Indentation in Python, and Comments in Python. We will also discuss different rules and examples for Python Statement, Python Indentation, Python Comment, and the Difference Between 'Docstrings' and 'Multi-line Comments. What is Statement in Python A Python statement is an instruction that the Python inte
7 min read
Python Continue Statement
Python Continue Statement skips the execution of the program block after the continue statement and forces the control to start the next iteration. Python Continue StatementPython Continue statement is a loop control statement that forces to execute the next iteration of the loop while skipping the rest of the code inside the loop for the current i
4 min read
How to Use IF Statement in MySQL Using Python
Prerequisite: Python: MySQL Create Table In this article, we are going to see how to use if statements in MySQL using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with
2 min read
How to Execute a SQLite Statement in Python?
In this article, we are going to see how to execute SQLite statements using Python. We are going to execute how to create a table in a database, insert records and display data present in the table. In order to execute an SQLite script in python, we will use the execute() method with connect() object: connection_object.execute("sql statement") Appr
2 min read
Python pass Statement
The Python pass statement is a null statement. But the difference between pass and comment is that comment is ignored by the interpreter whereas pass is not ignored. The Syntax of the pass statementpassWhat is pass statement in Python? When the user does not know what code to write, So user simply places a pass at that line. Sometimes, the pass is
3 min read
Python Match Case Statement
Developers coming from languages like C/C++ or Java know that there is a conditional statement known as a Switch Case. This Match Case is the Switch Case of Python which was introduced in Python 3.10. Here we have to first pass a parameter and then try to check with which case the parameter is getting satisfied. If we find a match we will execute s
9 min read
Python return statement
A return statement is used to end the execution of the function call and "returns" the result (value of the expression following the return keyword) to the caller. The statements after the return statements are not executed. If the return statement is without any expression, then the special value None is returned. A return statement is overall use
5 min read
with statement in Python
In Python, with statement is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Observe the following code example on how the use of with statement makes code cleaner. [GFGTABS] Python # file handling # 1) without using with statement file = open('file_
8 min read
Python break statement
Python break is used to terminate the execution of the loop.  Python break statement Syntax:Loop{ Condition: break }Python break statementbreak statement in Python is used to bring the control out of the loop when some external condition is triggered. break statement is put inside the loop body (generally after if condition).  It terminates the cur
4 min read
Check multiple conditions in if statement - Python
If-else conditional statement is used in Python when a situation leads to two conditions and one of them should hold true. Syntax: if (condition): code1else: code2[on_true] if [expression] else [on_false]Note: For more information, refer to Decision Making in Python (if , if..else, Nested if, if-elif)Multiple conditions in if statement Here we'll s
4 min read
Python Nested Dictionary
A Dictionary in Python works similarly to the Dictionary in the real world. The keys of a Dictionary must be unique and of immutable data types such as Strings, Integers, and tuples, but the key values can be repeated and be of any type. What is Python in Nested Dictionary? Nesting Dictionary means putting a dictionary inside another dictionary. Ne
3 min read
Python | Intersection of two nested list
This particular article aims at achieving the task of intersecting two list, in which each element is in itself a list. This is also a useful utility as this kind of task can come in life of programmer if he is in the world of development. Lets discuss some ways to achieve this task. Method 1: Naive Method This is the simplest method to achieve thi
5 min read
Python | Cumulative Nested Tuple Column Product
Sometimes, while working with records, we can have a problem in which we require to perform index wise multiplication of tuple elements. This can get complicated with tuple elements to be tuple and inner elements again be tuple. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using zip() + nested generator expression The
7 min read
Python: Update Nested Dictionary
A Dictionary in Python works similar to the Dictionary in the real world. Keys of a Dictionary must be unique and of immutable data types such as Strings, Integers, and tuples, but the key-values can be repeated and be of any type. Refer to the below article to get the idea about dictionaries: Python Dictionary Nested Dictionary: The nested diction
6 min read
Overriding Nested Class members in Python
Overriding is an OOP's (object-oriented programming) concept and generally we deal with this concept in Inheritance. Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes
2 min read
Python - Nested dictionary Combinations
Sometimes, while working with Python dictionaries, we can have a problem in which we need to construct all the combination of dictionary keys with different values. This problem can have application in domains such as gaming and day-day programming. Lets discuss certain way in which we can perform this task. Input : test_dict = {'gfg': {'is' : [6],
3 min read
Nested Decorators in Python
Everything in Python is an object. Even function is a type of object in Python. Decorators are a special type of function which return a wrapper function. They are considered very powerful in Python and are used to modify the behaviour of a function temporarily without changing its actual value. Nesting means placing or storing inside the other. Th
2 min read
Nested Lambda Function in Python
Prerequisites: Python lambda In Python, anonymous function means that a function is without a name. As we already know the def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions. When we use lambda function inside another lambda function then it is called Nested Lambda Function. Example 1: #
2 min read
Convert Python Nested Lists to Multidimensional NumPy Arrays
Prerequisite: Python List, Numpy ndarray Both lists and NumPy arrays are inter-convertible. Since NumPy is a fast (High-performance) Python library for performing mathematical operations so it is preferred to work on NumPy arrays rather than nested lists. Method 1: Using numpy.array(). Approach : Import numpy package.Initialize the nested list and
2 min read
Convert nested Python dictionary to object
Let us see how to convert a given nested dictionary into an object Method 1 : Using the json module. We can solve this particular problem by importing the json module and use a custom object hook in the json.loads() method. C/C++ Code # importing the module import json # declaringa a class class obj: # constructor def __init__(self, dict1): self.__
2 min read
Creating nested dataclass objects in Python
Dataclasses is an inbuilt Python module which contains decorators and functions for automatically adding special methods like __init__() and __repr__() to user-defined classes. Dataclass Object is an object built into the Dataclasses module. This function is used as a decorator to add special methods directly to a user-defined class. This decorator
3 min read
How to make a box with the help of nested loops using Python arcade?
Arcade library is modern framework currently used in making 2D games. Nested loop discussed here are analogous to nested loops in any other programming language. The following tutorial will step by step explain how to draw a box with the help of nested loops using Python's arcade module. Import arcade library.Here we will be using circles to form a
2 min read
How to iterate through a nested List in Python?
In this article, we are going to see how to iterate through a nested List. A list can be used to store multiple Data types such as Integers, Strings, Objects, and also another List within itself. This sub-list which is within the list is what is commonly known as the Nested List. Iterating through a Nested List Lets us see how a typical nested list
2 min read
Convert nested JSON to CSV in Python
In this article, we will discuss how can we convert nested JSON to CSV in Python. An example of a simple JSON file: As you can see in the example, a single key-value pair is separated by a colon (:) whereas each key-value pairs are separated by a comma (,). Here, "name", "profile", "age", and "location" are the key fields while the corresponding va
9 min read
Convert a nested for loop to a map equivalent in Python
In this article, let us see how to convert a nested for loop to a map equivalent in python. A nested for loop's map equivalent does the same job as the for loop but in a single line. A map equivalent is more efficient than that of a nested for loop. A for loop can be stopped intermittently but the map function cannot be stopped in between. Syntax:
3 min read
How to convert a MultiDict to nested dictionary using Python
A MultiDict is a dictionary-like object that holds multiple values for the same key, making it a useful data structure for processing forms and query strings. It is a subclass of the Python built-in dictionary and behaves similarly. In some use cases, we may need to convert a MultiDict to a nested dictionary, where each key corresponds to a diction
3 min read
Rename Nested Field in Spark Dataframe in Python
In this article, we will discuss different methods to rename the columns in the DataFrame like withColumnRenamed or select. In Apache Spark, you can rename a nested field (or column) in a DataFrame using the withColumnRenamed method. This method allows you to specify the new name of a column and returns a new DataFrame with the renamed column. Requ
3 min read
Python - Convert Lists to Nested Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to convert lists to nestings, i.e. each list value represents a new nested level. This kind of problem can have applications in many domains including web development. Let's discuss the certain way in which this task can be performed. Convert Lists to Nested D
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg