The Wayback Machine - https://web.archive.org/web/20241001164116/https://www.geeksforgeeks.org/conditional-statements-in-python/
Open In App

Conditional Statements in Python

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

Understanding and mastering Python’s conditional statements is fundamental for any programmer aspiring to write efficient and robust code. In this guide, we’ll delve into the intricacies of conditional statements in Python, covering the basics, advanced techniques, and best practices.

What are Conditional Statements?

Conditional Statements are statements in Python that provide a choice for the control flow based on a condition. It means that the control flow of the Python program will be decided based on the outcome of the condition. Now let us see how Conditional Statements are implemented in Python.

1. If Conditional Statement in Python

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

Syntax of If Statement:

if condition:
# Statements to execute if
# condition is true
Python
# if statement example
if 10 > 5:
    print("10 greater than 5")

print("Program ended")

Output
10 greater than 5
Program ended

2. If else Conditional Statements in Python

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

Syntax of Python If-Else: 

if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Python
# if..else statement example
x = 3
if x == 4:
    print("Yes")
else:
    print("No")

Output
No

3. Nested if..else Conditional Statements in Python

Nested if..else means an if-else statement inside another if statement. Or in simple words first, there is an outer if statement, and inside it another if – else statement is present and such type of statement is known as nested if statement. We can use one if or else if statement inside another if or else if statements.

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

4. If-elif-else Conditional Statements in Python

The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final “else” statement will be executed.

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

5. Ternary Expression Conditional Statements in Python

The Python ternary Expression determines if a condition is true or false and then returns the appropriate value in accordance with the result. The ternary Expression is useful in cases where we need to assign a value to a variable based on a simple condition, and we want to keep our code more concise — all in just one line of code.

Syntax of Ternary Expression

Syntax: [on_true] if [expression] else [on_false]
expression: conditional_expression | lambda_expr
Python
# Python program to demonstrate nested ternary operator
a, b = 10, 20

print("Both a and b are equal" if a == b else "a is greater than b"
        if a > b else "b is greater than a")

Output
b is greater than a

Best Practices for Using Conditional Statements

  1. Keep conditions simple and expressive for better readability.
  2. Avoid deeply nested conditional blocks; refactor complex logic into smaller, more manageable functions.
  3. Comment on complex conditions to clarify their purpose.
  4. Prefer the ternary operator for simple conditional assignments.
  5. Advanced Techniques:
  6. Using short-circuit evaluation for efficiency in complex conditions.
  7. Leveraging the any() and all() functions with conditions applied to iterables.
  8. Employing conditional expressions within list comprehensions and generator expressions.


Conditional Statements in Python – FAQs


What are Conditional Statements in Python?

Conditional statements in Python are used to execute a specific block of code based on the truth value of a condition. The most common conditional statements in Python are if, elif, and else. These allow the program to react differently depending on whether a condition (or a series of conditions) is true or false.

x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")

What is a Conditional Expression in Python?

A conditional expression (also known as a ternary operator) in Python provides a method to simplify conditional statements. It allows for a quick definition of a condition and two possible outcomes (one if the condition is true, and one if the condition is false). The syntax is value_if_true if condition else value_if_false.

# Conditional expression example
x = 5
result = "High" if x > 10 else "Low"
print(result) # Outputs: "Low"

What are Decision-Making Statements in Python?

Decision-making statements in Python help to control the flow of execution based on certain conditions. These include:

  • if statement: Executes a block of code if a specified condition is true.
  • if-else statement: Executes one block of code if the condition is true, and another block if the condition is false.
  • elif (else if) statement: Checks multiple conditions in a sequence and executes a block of code as soon as one of the conditions evaluates to true.
  • Nested if statements: You can nest if statements within another if or else block to create complex decision trees.

What are Conditional Selection Statements in Python?

Conditional selection statements refer to the use of if, elif, and else statements that select specific blocks of code to execute based on conditions. These statements are fundamental for branching in programming, allowing different outcomes depending on the input or state of the program.

What are the Conditional Loops in Python?

While Python supports loops that can incorporate conditions, the term “conditional loops” might specifically refer to loops that run based on a condition. Python provides two primary types of such loops:

  • while loop: Continues to execute as long as a given condition is true. It checks the condition before executing the loop body.
# while loop example
x = 5
while x < 10:
print(x)
x += 1
  • for loop: Iterates over a sequence (like a list, tuple, or string) and executes the loop body for each item in the sequence. Although not traditionally a “conditional” loop, it can incorporate conditions using break and continue to control the loop execution dynamically.
# for loop example with condition
for i in range(10):
if i == 5:
break # Exit the loop when i is 5
print(i)

These explanations outline how Python uses conditional statements and expressions to manage the flow of execution and make decisions within programs, crucial for creating dynamic and responsive applications



    Previous Article
    Next Article

    Similar Reads

    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
    Loops and Control Statements (continue, break and pass) in Python
    Python programming language provides the following types of loops to handle looping requirements. Python While Loop Until a specified criterion is true, a block of statements will be continuously executed in a Python while loop. And the line in the program that follows the loop is run when the condition changes to false. Syntax of Python Whilewhile
    4 min read
    Difference between continue and pass statements in Python
    Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore that condition. These can be done by loop control statements. Loop control statements change execution from its normal sequence. When execution leaves a scop
    3 min read
    How to Execute many SQLite Statements in Python?
    In SQLite using the executescript() method, we can execute multiple SQL statements/queries at once. The basic execute() method allows us to only accept one query at a time, so when you need to execute several queries we need to arrange them like a script and pass that script to the executescript() method. executescript() can be able to execute seri
    3 min read
    Python - Multi-Line Statements
    In this article, we are going to understand the concept of Multi-Line statements in the Python programming language. Statements in Python: In Python, a statement is a logical command that a Python interpreter can read and carry out. It might be an assignment statement or an expression in Python. Multi-line Statement in Python: In Python, the statem
    3 min read
    Jump Statements in Python
    In any programming language, a command written by the programmer for the computer to act is known as a statement. In simple words, a statement can be thought of as an instruction that programmers give to the computer and upon receiving them, the computer acts accordingly. There are various types of statements in programming and one such type of sta
    4 min read
    Alternatives to Case/Switch Statements in Python
    In many programming languages, the case or switch statement is a control flow mechanism that allows a variable to be tested for equality against a list of values, with each value associated with a block of code to be executed. However, Python does not have a built-in case or switch statement. Instead, Python developers use various alternative struc
    3 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
    Conditional Decorators in Python
    In Python, decorators are functions or classes that wrap around a function as a wrapper by taking a function as input and returning out a callable. They allow the creation of reusable building code blocks that can either change or extend behavior of other functions. Conditional Decorators Given a condition, the idea here is to execute code or basic
    2 min read
    Conditional Inheritance in Python
    It happens most of the time that given a condition we need to decide whether a particular class should inherit a class or not, for example given a person, if he/she is eligible for an admission in a university only then they should be a student otherwise they should not be a student. Let's consider an example, where given a condition, we want a cla
    3 min read
    Adding Conditional Formatting to Excel Using Python Openpyxl
    Adding conditional formatting using openpyxl is an easy and straightforward process. While working with Excel files, conditional formatting is useful for the visualization of trends in the data, highlighting crucial data points, and making data more meaningful and understandable. In this article, we will give a detailed step-by-step explanation for
    5 min read
    Chain multiple statements within Psycopg2
    In this tutorial, we will see how to chain multiple statements with psycopg2 which is a PostgreSQL database adapter for Python. Chaining is supported by most SQL databases and can be used in various types of SQL clients, such as command-line interfaces, web-based management interfaces, and programming language libraries like psycopg2. let's underst
    8 min read
    Using Apply in Pandas Lambda functions with multiple if statements
    In this article, we are going to see how to apply multiple if statements with lambda function in a pandas dataframe. Sometimes in the real world, we will need to apply more than one conditional statement to a dataframe to prepare the data for better analysis. We normally use lambda functions to apply any condition on a dataframe, Syntax: lambda arg
    3 min read
    Python3 - if , if..else, Nested if, if-elif statements
    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 conditio
    7 min read
    Conditional operation on Pandas DataFrame columns
    Suppose you have an online store. The price of the products is updated frequently. While calculating the final price on the product, you check if the updated price is available or not. If not available then you use the last price available. Solution #1: We can use conditional expression to check if the column is present or not. If it is not present
    4 min read
    Mahotas – Conditional Dilating Image
    In this article we will see how we can do conditional dilating of the image in mahotas. Dilation adds pixels to the boundaries of objects in an image, while erosion removes pixels on object boundaries. The number of pixels added or removed from the objects in an image depends on the size and shape of the structuring element used to process the imag
    3 min read
    Mahotas – Conditional Eroding Image
    In this article we will see how we can do conditional eroding of the image in mahotas. Erosion is one of two fundamental operations (the other being dilation) in morphological image processing from which all other morphological operations are based. It was originally defined for binary images, later being extended to grayscale images, and subsequen
    2 min read
    Mahotas – Conditional Watershed of Image
    In this article, we will see how we can do a conditional watershed of the image in mahotas. In the study of image processing, a watershed is a transformation defined on a grayscale image. The name refers metaphorically to a geological watershed, or drainage divide, which separates adjacent drainage basins. In this tutorial, we will use the “Lena” i
    2 min read
    Django Conditional Expressions in Queries
    The conditional expressions allow developers to make decisions and manipulate data within queries, templates, and Python code, making it easier to create complex and dynamic web applications. In this article, we'll delve into the world of conditional expressions in Django and explore how they can be used to enhance your web development projects. Se
    4 min read
    Important differences between Python 2.x and Python 3.x with examples
    In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
    5 min read
    Reading Python File-Like Objects from C | Python
    Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
    3 min read
    Python | Add Logging to a Python Script
    In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
    2 min read
    Python | Add Logging to Python Libraries
    In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
    2 min read
    Python | Index of Non-Zero elements in Python list
    Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
    6 min read
    MySQL-Connector-Python module in Python
    MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
    2 min read
    Python - Read blob object in python using wand library
    BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
    2 min read
    twitter-text-python (ttp) module - Python
    twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
    3 min read
    Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
    Context Managers are the tools for wrapping around arbitrary (free-form) blocks of code. One of the primary reasons to use a context manager is resource cleanliness. Context Manager ensures that the process performs steadily upon entering and on exit, it releases the resource. Even when the wrapped code raises an exception, the context manager guar
    7 min read
    Creating and updating PowerPoint Presentations in Python using python - pptx
    python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
    4 min read
    Python Debugger – Python pdb
    Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to the Python standard library. It is actually defined as the class Pdb which internally makes use of bdb(basic debugger functions) and cmd (support for line-oriented command interpreters) modules. The major advantage of pdb is it runs purely in the command line
    5 min read
    Article Tags :
    Practice Tags :