Decision-making is a crucial part of programming. Python allows you to write code that makes decisions using if-else
statements and conditional operators. In this article, we’ll dive into how these work and see examples to help you get started.
What Are if-else
Statements?
if-else
statements allow your program to execute certain pieces of code based on conditions. Think of it as asking a question: "If this is true, do this; otherwise, do that."
Basic Syntax
if condition:
# Code to run if the condition is True
else:
# Code to run if the condition is False
Example 1: Simple if-else
Statement
Let’s check if someone is old enough to vote:
age = 18
if age >= 18:
print("You are eligible to vote!")
else:
print("You are not eligible to vote.")
Output:
You are eligible to vote!
Here:
The
if
checks if theage
is greater than or equal to 18.If the condition is
True
, it runs the first block of code.If the condition is
False
, it runs theelse
block.
What Are Conditional Operators?
Conditional operators compare values and return True
or False
. These are often used in if-else
statements.
Common Conditional Operators
Operator | Description | Example (x = 10, y = 20 ) |
== | Equal to | x == y → False |
!= | Not equal to | x != y → True |
< | Less than | x < y → True |
> | Greater than | x > y → False |
<= | Less than or equal to | x <= y → True |
>= | Greater than or equal to | x >= y → False |
Using elif
for Multiple Conditions
Sometimes, you need to check more than two conditions. This is where elif
comes in (short for "else if").
Example 2: Grading System
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Output:
Grade: B
Here:
The program checks each condition in order.
When a condition is
True
, the corresponding block of code is executed, and the rest are ignored.
Nested if
Statements
You can place one if
statement inside another. This is called a nested if
.
Example 3: Nested Conditions
age = 20
is_student = True
if age >= 18:
if is_student:
print("You are a student and an adult.")
else:
print("You are an adult but not a student.")
else:
print("You are not an adult.")
Output:
You are a student and an adult.
Logical Operators
Sometimes, you need to combine multiple conditions. Python provides logical operators to handle this.
Common Logical Operators
Operator | Description | Example |
and | Returns True if both are True | (x > 5 and y > 10) → True |
or | Returns True if at least one is True | (x > 15 or y > 10) → True |
not | Reverses the condition | not (x > 5) → False |
Example 4: Using Logical Operators
age = 25
is_employed = True
if age > 18 and is_employed:
print("You are an employed adult.")
else:
print("You are either not an adult or not employed.")
Output:
You are an employed adult.
Ternary (One-Line if-else
)
For simple conditions, Python lets you write if-else
statements in one line.
Example 5: Ternary Operator
age = 16
message = "Adult" if age >= 18 else "Minor"
print(message)
Output:
Minor
Common Mistakes to Avoid
Forgetting the Colon (
:
):if age >= 18 # Error: Missing colon print("Adult")
Indentation Errors: Python uses indentation to define code blocks. Ensure all lines in the same block are indented equally.
Not Using Comparison Operators:
if age: # This checks if age is not zero, not if age >= 18 print("Adult")
Practice Problems
Write a program to check if a number is even or odd.
Create a program that categorizes a person based on age:
Child: 0-12 years
Teen: 13-19 years
Adult: 20+ years.
Write a program to check if a year is a leap year or not.
Conclusion
if-else
statements and conditional operators are the building blocks of decision-making in Python. They let your programs adapt to different scenarios, making them dynamic and intelligent. Master these concepts, and you’ll be ready to tackle more complex logic in programming.
Happy coding! 🚀