You can use conditional statements to save time when automating tasks or analyzing data. For example, you can write code that sorts files into folders based on their type. Or, you can analyze sales data and flag transactions above a certain amount.
What are Conditional Statements in Python?
A Python conditional statement executes a block of code only if a specified condition is true. These statements use if
, elif
(else if), and else
keywords to control program execution.
For example, you can check if a user’s age is 18 or older before granting access to certain features. This ensures that only eligible users proceed.
Conditional statements make your code flexible. They allow programs to respond to different inputs or situations. This is crucial for building any useful application.
Here are a few reasons why conditional statements help you:
- Handle different inputs: Your program can react differently based on user input.
- Create dynamic behavior: Code can adapt as conditions change.
- Build robust applications: You can manage various scenarios, preventing errors.
- Automate decision-making: Programs can make choices without human intervention.
In this course, you will learn the fundamentals of Python: from basic syntax to mastering data structures, loops, and functions. You will also explore OOP concepts and objects to build robust programs.
Using the if Statement
The if
statement is the most basic conditional statement. It checks if a condition is true. If it is, the code inside the if
block runs.
Here is the basic syntax:
if condition:
# Code to execute if the condition is true
The condition must be an expression that evaluates to True
or False
. Python evaluates this expression. If the result is True
, the indented code below the if
statement runs.
Example: Checking a Number
You can use an if
statement to check if a number is positive.
number = 10
if number > 0:
print("The number is positive.")
When you run this code, it prints “The number is positive.” because 10 > 0
is True
.
Example: User Authentication
Consider a simple authentication system.
username = "admin"
if username == "admin":
print("Welcome, administrator!")
This code checks if the username
variable is equal to “admin”. If it is, the welcome message displays.
Adding else for Alternatives
The else
statement works with if
. It provides an alternative code block to run when the if
condition is False
.
Here is the basic syntax:
if condition:
# Code to execute if the condition is true
else:
# Code to execute if the condition is false
The else
block runs only when the if
condition is not met. You do not need a condition for else
.
Example: Checking Age for Access
You can use if
and else
to control access based on age.
age = 17
if age >= 18:
print("Access granted.")
else:
print("Access denied. You must be 18 or older.")
Since age
is 17, age >= 18
is False
. The code inside the else
block runs, printing “Access denied. You must be 18 or older.”
Example: Even or Odd Check
You can determine if a number is even or odd using the modulo operator (%
).
num = 7
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Here, 7 % 2
is 1, so num % 2 == 0
is False
. The else
block runs, printing “The number is odd.”
Using elif for Multiple Conditions
The elif
(short for “else if“) statement lets you check multiple conditions sequentially. If the if
condition is False
, Python checks the first elif
condition. If that’s also False
, it checks the next elif
, and so on. If all if
and elif
conditions are False
, the else
block runs (if present).
Here is the basic syntax:
if condition1:
# Code if condition1 is true
elif condition2:
# Code if condition2 is true
elif condition3:
# Code if condition3 is true
else:
# Code if all conditions are false
Python stops checking conditions as soon as it finds one that is True
. Only the code block for the first True
condition executes.
Example: Grading System
You can create a simple grading system using elif
.
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Here, score >= 90
is False
. Then, score >= 80
is True
, so it prints “Grade: B” and skips the rest.
Example: Time-based Greetings
You can display different greetings based on the time of day.
import datetime
current_hour = datetime.datetime.now().hour
if current_hour < 12:
print("Good morning!")
elif current_hour < 18:
print("Good afternoon!")
else:
print("Good evening!")
This code gets the current hour. It then uses if
, elif
, and else
to print an appropriate greeting.
Combining Conditions
You can combine multiple conditions using logical operators: and
, or
, and not
.
and
: Both conditions must beTrue
.or
: At least one condition must beTrue
.not
: Reverses the truth value of a condition.
Example: Age and Membership
age = 25
is_member = True
if age >= 18 and is_member:
print("Welcome to the exclusive content area.")
else:
print("You need to be 18+ and a member.")
Here, both age >= 18
and is_member
are True
, so the message prints.
Example: Weekend or Holiday
day_of_week = "Sunday"
is_holiday = False
if day_of_week == "Saturday" or day_of_week == "Sunday" or is_holiday:
print("Enjoy your day off!")
else:
print("It's a workday.")
Since day_of_week
is “Sunday”, one of the or
conditions is True
, and the day off message displays.
Nested Conditional Statements
You can place conditional statements inside other conditional statements. This is called nesting. It helps handle more complex logic.
Example: User Status Check
is_logged_in = True
is_admin = False
if is_logged_in:
print("User is logged in.")
if is_admin:
print("Welcome, administrator!")
else:
print("Welcome, regular user.")
else:
print("Please log in.")
First, it checks if is_logged_in
is True
. Since it is, the nested if-else checks is_admin
. Because is_admin
is False
, it prints “Welcome, regular user.”
Best Practices for Conditional Statements
- Keep conditions simple: Complex conditions can be hard to read. Break them down if needed.
- Use meaningful variable names: This makes your conditions easier to understand.
- Indent consistently: Python relies on indentation for code blocks.
- Avoid excessive nesting: Too many nested
if
statements can make code difficult to manage. Consider refactoring with functions or logical operators. - Use
elif
instead of multipleif
statements: If conditions are mutually exclusive,elif
is more efficient and clearer.