In your everyday lives, you make choices based on different situations, like deciding whether to watch a movie or a web series. Similarly, in programming, you need to make decisions and take different actions based on specific conditions. In Python, you have a useful tool for this called conditional or selection statements.
Conditional statements help you control the flow of your programs by checking conditions and executing specific actions based on those conditions. For example, you can instruct your program to display an umbrella icon if it is raining, and a sun icon if it’s not. This capability makes your programs more dynamic and efficient.
Table of Contents
What is conditional statement
A conditional statement allows a program to make decisions based on certain conditions. It execute a block of code based on a certain condition. It is used to control the flow of a program.
Types of Conditional Statements:
if
statement
The if
statement is used to specify a condition and executes the block of code only if the condition is True
.
Syntax:
if condition:
statement 1
statement 2
Python- The condition is an expression that evaluates to either
True
orFalse
. - The colon
:
after theif
statement is important because it indicates the start of the code block. - The block of code inside
if
must be indented (typically 4 spaces).
for example:
num = 124
if num > 0:
print("The number is positive.") # output: The number is positive.
Pythonif-else
statement
Python also provide you the if-else
statement, which allows you to execute different blocks of code based on a condition. Basically, if-else
statement is used to execute one block of code if the condition is true which is if block, and another block of code if the condition is false that is else block.
Syntax:
if condition:
# Code block executed if the condition is True
statements
else:
# Code block executed if the condition is False
statements
Python- The
if-else
statement follows the same indentation rules as theif
statement. - The colon
:
after theelse
statement used to indicate the beginning of the else code block. - If the condition is
True
, the if block runs and if the condition isFalse
, the else block runs.
for example:
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
# Output:
# You are not eligible to vote
PythonNow, as the condition age >= 18
is False
, the else
block is executed.
elif
statement
The if-elif
statement allows you to check multiple conditions and execute different blocks of code based on the True
condition. This is also called if-else
ladder.
Syntax:
1. Single elif
if condition1:
# code block for condition1
elif condition2:
# code block for condition2
Python2. Multiple elif
if condition1:
# code block for condition1
elif condition2:
# code block for condition2
elif condition3:
# code block for condition3
Python3. If-elif-else
if condition1:
# code block for condition1
elif condition2:
# code block for condition2
# ... more elif statements if needed
else:
# code block if none of the conditions are true
Python- The program first checks the initial
if
statement. If it’sTrue
, that block runs, and the rest are skipped. If the initial condition isFalse
, the program will move on to the next condition, which is written aselif
. - There is no strict limit to the number of elif statements. You can have as many elif statements as needed.
- The program will check each
elif
condition, one by one in order, until it finds a condition that isTrue
. - Once it finds a
True
condition, the code inside that particular elif block will be executed, and python will skip the remaining blocks. - The
else
block executes only if all previous conditions areFalse
. The else statement is not required after everyelif
statement. It is optional.
for example
marks = 75
if marks >= 90:
print("Grade: A+")
elif marks >= 80:
print("Grade: A")
elif marks >= 70:
print("Grade: B")
else:
print("Grade: C")
# Output:
# Grade: B
PythonNested if-else
statement
A nested if-else
or nested if
or nested elif
statement is an if-elif-else
(each optional other than if) statement inside another if
or else
or elif
block. This structure allows for checking multiple conditions in a more organized way.
Here are four different syntax examples for nested if statements but you can create it according to your need
Syntax 1
if condition1:
# Outer if block
if condition2:
# Inner if block
else:
# Inner else block
else:
# Outer else block
PythonSyntax 2
if condition1:
# Outer if block
if condition2:
# Inner if block
elif condition3:
# Inner elif block
else:
# Inner else block
else:
# Outer else block
PythonSyntax 3
if condition1:
# Outer if block
else:
if condition2:
# Inner if block
elif condition3:
# Inner elif block
# Outer else block
PythonSyntax 4
if condition1:
# Outer if block
if condition2:
# Inner if block
else:
# Inner else block
elif condition3:
# Outer elif block
if condition4:
# Inner if block
else:
# Inner else block
else:
# Outer else block
Python- First, the program evaluates the outer (level 1)
if
orelif
orelse
statement to check if it is true or false. - If the outer
if
orelif
orelse
condition is true, the program proceeds to the inner (level 2) if’s statements and evaluates its condition. - If the inner
if
condition is also true, the code inside the innerif
block is executed. - If either the outer or inner
if
condition is false, the code inside the innerif
block is skipped, and the program continue.
for example:
age = int(input("Enter your age: "))
if age >= 18: # First condition check
print("You are an adult.")
if age >= 60: # Second condition inside first if
print("You are a senior citizen.")
else:
print("You are not a senior citizen yet.")
else:
print("You are a minor.")
# Output:
# Enter your age: 25
# You are an adult.
# You are not a senior citizen yet.
PythonCommon Mistakes
- Forgetting the colon
:
at the end ofif
,elif
, orelse
lines.
age = 18
if age >= 18 # Missing colon
print("You are an adult.")
PythonError:
IndentationError: expected an indented block
Bash- using assignment operator instead of comparision operator.
x = 5
if x = 5: # Single '=' is for assignment, not comparison
print("x is 5")
PythonError:
SyntaxError: invalid syntax
Bash- Not Using else When Necessary.
score = 40
if score >= 50:
print("You passed!") # No output if score < 50
PythonIssue:
If score = 40
, nothing happens
- Using
elif
Instead ofelse
When No Further Condition Is Needed
marks = 30
if marks >= 50:
print("Pass")
elif marks < 50: # Unnecessary `elif`
print("Fail")
PythonCorrect code
marks = 30
if marks >= 50:
print("Pass")
else: # Use `else` since it's the only alternative
print("Fail")
Python- Forgetting to Handle All Possible Cases
number = 0
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
PythonCorrected code
f number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero") # Handle all cases
PythonUses of conditional statement
Conditional statements serve several important purposes:
- Decision Making: They enable programs to make choices based on different situations, making the code more flexible and intelligent.
- User Interaction: They allow programs to respond to user actions, such as clicking a button, by deciding what to do next.
- Error Handling: Conditional statements can check if inputs are valid. For instance, if a user is asked to enter a number, the program can verify whether the input is correct.
- Simplifying Logic: They help break down complex problems into simpler, manageable parts.
Conclusion
Understanding if-else
statements is crucial for writing logical and efficient Pythonprograms. By avoiding common mistakes, you can improve the readability, maintainability, and correctness of your code.
Always ensure that all possible conditions are handled, use elif
where appropriate, and write concise, structured logic to enhance clarity. This will not only make your code more effective but also easier for others to understand and work with.