Conditional Statements in Python
Last Updated :
18 Feb, 2025
Conditional statements in Python are used to execute certain blocks of code based on specific conditions. These statements help control the flow of a program, making it behave differently in different situations.
If Conditional Statement in Python
If statement is the simplest form of a conditional statement. It executes a block of code if the given condition is true.
Example:
Python
age = 20
if age >= 18:
print("Eligible to vote.")
Short Hand if
Short-hand if statement allows us to write a single-line if statement.
Example:
Python
age = 19
if age > 18: print("Eligible to Vote.")
This is a compact way to write an if statement. It executes the print statement if the condition is true.
If else Conditional Statements in Python
Else allows us to specify a block of code that will execute if the condition(s) associated with an if or elif statement evaluates to False. Else block provides a way to handle all other cases that don't meet the specified conditions.
Example:
Python
age = 10
if age <= 12:
print("Travel for free.")
else:
print("Pay for ticket.")
Short Hand if-else
The short-hand if-else statement allows you to write a single-line if-else statement.
Example:
Python
marks = 45
res = "Pass" if marks >= 40 else "Fail"
print(f"Result: {res}")
Note: This method is also known as ternary operator. Ternary Operator essentially a shorthand for the if-else statement that allows us to write more compact and readable code, especially for simple conditions.
elif Statement
elif statement in Python stands for "else if." It allows us to check multiple conditions , providing a way to execute different blocks of code based on which condition is true. Using elif statements makes our code more readable and efficient by eliminating the need for multiple nested if statements.
Example:
Python
age = 25
if age <= 12:
print("Child.")
elif age <= 19:
print("Teenager.")
elif age <= 35:
print("Young adult.")
else:
print("Adult.")
Here, the first condition x > 15 is False, so the elif condition x > 5 is checked next. Since it is True, the corresponding block is executed.
Nested if..else Conditional Statements in Python
Nested if..else means an if-else statement inside another if statement. We can use nested if statements to check conditions within conditions.
Python
age = 70
is_member = True
if age >= 60:
if is_member:
print("30% senior discount!")
else:
print("20% senior discount.")
else:
print("Not eligible for a senior discount.")
Output30% senior discount!
Ternary Conditional Statement in Python
A ternary conditional statement is a compact way to write an if-else condition in a single line. Itâs sometimes called a "conditional expression."
Example:
Python
# Assign a value based on a condition
age = 20
s = "Adult" if age >= 18 else "Minor"
print(s)
Here:
- If age >= 18 is True, status is assigned "Adult".
- Otherwise, status is assigned "Minor".
Match-Case Statement in Python
match-case statement is Python's version of a switch-case found in other languages. It allows us to match a variable's value against a set of patterns.
Example:
Python
number = 2
match number:
case 1:
print("One")
case 2 | 3:
print("Two or Three")
case _:
print("Other number")
Output:
Two or Three
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
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial - Python is one of the most popular programming languages today, known for its simplicity, extensive features and library support. Its clean and straightforward syntax makes it beginner-friendly, while its powerful libraries and frameworks makes it perfect for developers. Python is:
9 min read
Getting Started with Python Programming
To get started with Python, let's first finish the installation steps. Here's a basic guide to setup Python in your system. Install PythonBefore starting this Python course first, you need to install Python on your computer. To install Python on your computer, follow these steps: Download Python: Go
2 min read
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Printing Output using print() in PythonAt its co
7 min read
Data Types
Python String
A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1. [GFGTABS] Python s = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # updat
5 min read
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
5 min read
Python Tuples
A tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can hold elements of different data types. The main characteristics of tuples are being ordered , heterogene
7 min read
Python Sets
Python set is an unordered collection of multiple items having different datatypes. In Python, sets are mutable, unindexed and do not contain duplicates. The order of elements in a set is not preserved and can change. Creating a Set in PythonIn Python, the most basic and efficient method for creatin
11 min read
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
5 min read
Python Arrays
Lists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences: Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
9 min read
Python Operators
In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. Eg- + , * , /,
6 min read
Conditional Statements in Python
Conditional statements in Python are used to execute certain blocks of code based on specific conditions. These statements help control the flow of a program, making it behave differently in different situations. If Conditional Statement in PythonIf statement is the simplest form of a conditional st
6 min read
Loops in Python - For, While and Nested Loops
Loops in Python are used to repeat actions efficiently. The main types are For loops (counting through items) and While loops (based on conditions). Additionally, Nested Loops allow looping within loops for more complex tasks. While all the ways provide similar basic functionality, they differ in th
9 min read
Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it ov
10 min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read