Python tutorials > Core Python Fundamentals > Control Flow > How to use `if`/`elif`/`else`?
How to use `if`/`elif`/`else`?
Understanding Conditional Statements in Python: if/elif/else
Conditional statements are fundamental building blocks in programming. They allow your program to make decisions based on different conditions. In Python, the This tutorial will guide you through the syntax, usage, and best practices of using if
, elif
(short for 'else if'), and else
statements provide a way to control the flow of execution based on these conditions.if
, elif
, and else
in Python.
The Basic `if` Statement
The In the example above, the condition if
statement checks if a condition is true. If the condition is true, the code block indented below the if
statement is executed. If the condition is false, the code block is skipped.age >= 18
is true (since age is 20), so the message "You are an adult." is printed.
age = 20
if age >= 18:
print("You are an adult.")
The `if`/`else` Statement
The In the example above, the condition if/else
statement provides an alternative code block to execute when the condition in the if
statement is false. If the condition is true, the code block under the if
statement is executed. Otherwise, the code block under the else
statement is executed.age >= 18
is false (since age is 15), so the message "You are a minor." is printed.
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
The `if`/`elif`/`else` Statement
The In the example above, the condition if/elif/else
statement allows you to check multiple conditions in sequence. The elif
(short for 'else if') statement checks another condition only if the previous if
or elif
conditions were false. The else
statement provides a default code block to execute if none of the previous conditions were true.score >= 90
is false, so the next condition score >= 70
is checked. Since this is true (score is 75), the message "Good job!" is printed. Note that even though `score >= 50` is also true, the code block under it is not executed because a previous `elif` condition was already met.
score = 75
if score >= 90:
print("Excellent!")
elif score >= 70:
print("Good job!")
elif score >= 50:
print("You passed.")
else:
print("You failed.")
Concepts Behind the Snippet
The core concept is conditional execution. The `if`, `elif`, and `else` keywords enable your program to follow different paths of execution depending on the state of your data. This allows programs to respond intelligently to varying inputs and situations. Boolean Logic: Conditional statements rely on boolean logic. The conditions you evaluate must ultimately resolve to either True
or False
. Python uses comparison operators (==
, !=
, >
, <
, >=
, <=
) and logical operators (and
, or
, not
) to create these boolean expressions.
Real-Life Use Case Section
User Authentication: Imagine a website where users log in. The Game Development: In a game, the Data Validation: When processing user input or data from a file, conditional statements are used to validate the data. For example, you might check if a user has entered a valid email address format or if a number falls within an acceptable range.if
statement checks if the entered username and password match the records in the database. If they match, the user is granted access; otherwise, an error message is displayed using the else
statement.if
/elif
/else
statements can control character movement based on user input (e.g., pressing the 'W' key moves the character forward). They can also determine the outcome of a game event (e.g., checking if a player's health is zero, in which case the game is over).
Best Practices
if
statements can make your code difficult to read and maintain. Consider refactoring your code to use functions or other techniques to reduce nesting.elif
can improve readability and efficiency.else
statement can help you handle unexpected cases and prevent errors.
Interview Tip
When asked about A common interview question might be: "Describe a scenario where you would use an You should also be prepared to discuss the time complexity of different conditional structures. While the fundamental conditional checks are generally O(1), the overall complexity of a function or program can be affected by the number of conditional branches and the code executed within each branch.if
/elif
/else
statements in an interview, be prepared to explain the syntax, usage, and purpose of each keyword. Also, be ready to discuss best practices and common pitfalls.if
/elif
/else
statement." Prepare a few examples beforehand.
When to use them
Use Use Use if
statements whenever you need to execute code conditionally based on whether a condition is true or false.if/else
statements when you need to execute one block of code if a condition is true and another block of code if the condition is false.if/elif/else
statements when you need to check multiple conditions in sequence and execute a different block of code for each condition. This is particularly useful when you have mutually exclusive conditions.
Memory Footprint
The memory footprint of However, complex conditions involving large data structures can indirectly increase memory usage. Optimizing the data structures and the logic within the conditional blocks can help reduce memory consumption.if
/elif
/else
statements themselves is generally negligible. They don't allocate significant amounts of memory directly. The memory usage primarily depends on the variables used in the conditions and the code executed within each branch of the conditional statement.
Alternatives
While Ternary Operator: For simple Dictionaries for dispatch: If you're checking for specific values and performing different actions based on them, a dictionary can act as a 'dispatch table'. Match statement (Python 3.10+): The if
/elif
/else
are fundamental, there are situations where alternatives might be more concise or readable:if/else
assignments, the ternary operator (value_if_true if condition else value_if_false
) can be used.match
statement provides a more structured way to handle multiple conditions, similar to a switch
statement in other languages.
Pros
Cons
else
case or having incorrect conditions can lead to unexpected behavior.
FAQ
-
What happens if none of the `if` or `elif` conditions are true?
If none of theif
orelif
conditions are true, the code block under theelse
statement (if present) is executed. If there is noelse
statement, no code block is executed. -
Can I nest `if` statements inside other `if` statements?
Yes, you can nestif
statements inside otherif
statements. However, deep nesting can make your code difficult to read and maintain. It's often better to refactor your code to avoid deep nesting. -
Are parentheses required around the conditions in `if` statements?
No, parentheses are not required around the conditions inif
statements in Python, but can be added for readability or precedence control when combining several conditions withand
andor
.