The if Statement
The simplest conditional statement in Python uses theif keyword. When the condition provided after if evaluates to True, the following indented block of code is executed:
Always remember to end your
if statement line with a colon (:). Proper indentation is critical for Python to correctly interpret which statements belong to the block.Practical Example with User Input
Consider a scenario where we prompt the user to enter their age. We then use anif statement to determine if the user is 18 or older, outputting an appropriate message accordingly. For example, if a user enters the age 22, the program will confirm that the user is an adult:
The if-else Statement
Sometimes, you need to execute one block of code when a condition is true and a different block when it is false. Use theelse keyword to provide an alternative:
else will run.
The if-elif-else Chain
For situations involving multiple conditions, Python’selif keyword lets you check additional expressions sequentially. This structure allows you to have several branching paths:
- Python first evaluates the
ifcondition. - If it evaluates to False, the program checks the
elifcondition. - If the
elifcondition is also False, theelseblock is executed.
elif or else) are ignored:
Nested Conditional Statements
You can nest conditional statements inside another to evaluate further conditions. For example, if you want to give a special message when a user’s age is exactly 18, use a nestedif:
- The outer
ifchecks if the user is an adult (18 or older). - If true, the inner
iffurther checks whether the age is exactly 18. - If the inner condition is False, it indicates that the user is older than 18.
Using nested conditional statements helps create a more detailed decision-making process, allowing you to handle complex conditions efficiently.
Summary of Conditional Statements
| Statement Type | Description | Example Usage |
|---|---|---|
| if | Executes code when a condition is True | if condition: print("True condition") |
| if-else | Provides an alternative when the condition is False | if condition: print("True") else: print("False") |
| if-elif-else | Evaluates multiple conditions sequentially | if a: ... elif b: ... else: ... |
| Nested if | Allows deeper inspection by placing an if within an if | if age>=18: if age==18: print("Exactly 18") else: print("Above 18") |
Conclusion
This guide covered the fundamentals of conditional statements in Python. We examined the basicif statement, introduced the alternative else clause, explored chaining multiple conditions with elif, and demonstrated how to nest conditionals for refined control. These techniques form the backbone of decision-making in Python programming.
Happy coding!