Contents
Conditional Statements
Conditional Statements
Conditional statements control the flow of your Python code by executing different actions based on specified conditions. They’re fundamental for building decision-making in programs, making them crucial for writing logical and efficient Python code.
Types of Conditional Statements in Python
1. if
Statement
The if
statement executes a block of code only if a specified condition is True
. If the condition is False
, the block will not execute.
Syntax of the if
statement:
if condition:
# Code to execute if condition is true
Example:
age = 18
if age >= 18:
print("You are eligible to vote.")
Output:
You are eligible to vote.
2. if-else
Statement
The if-else
statement expands on the if
statement by adding an alternate block of code if the condition is False
.
Syntax of if-else
:
if condition:
# Code if condition is true
else:
# Code if condition is false
Example:
score = 50
if score >= 60:
print("Passed")
else:
print("Failed")
Output:
Failed
3. Nested if-else
Statement
A nested if-else
is when an if-else
block is placed inside another if-else
block. This allows you to create more complex conditions.
Example:
number = 15
if number > 10:
if number < 20:
print("Number is between 10 and 20")
else:
print("Number is 20 or more")
else:
print("Number is 10 or less")
Output:
Number is between 10 and 20
4. if-elif-else
Statement
The if-elif-else
ladder provides multiple conditions to check sequentially. Once a condition is found True
, the corresponding block is executed, and the rest are bypassed.
Example:
day = "Wednesday"
if day == "Monday":
print("Start of the work week")
elif day == "Wednesday":
print("Midweek")
elif day == "Friday":
print("End of the work week")
else:
print("It's the weekend!")
Output:
Midweek
5. Ternary Expression (Conditional Expression)
The ternary expression allows you to write a conditional statement in a single line. It’s ideal for simple conditions that can be concisely expressed.
Syntax:
value_if_true if condition else value_if_false
Example:
x, y = 5, 10
result = "x is greater" if x > y else "y is greater or equal"
print(result)
Output:
y is greater or equal