Hello! In our last lesson, you learned how to make your programs interactive by taking user input and presenting formatted output. This gave your code a way to communicate with the outside world. Now, we'll give it the ability to think.
This lesson introduces one of the most fundamental concepts in programming: conditional logic. You will learn how to write code that makes decisions and executes different actions based on specific conditions. This is the core of what makes programs dynamic and intelligent rather than just a fixed sequence of commands. We will cover the if, elif, and else statements, which allow you to control the flow of your program. This is a critical skill for both of your goals: an ethical hacking tool must react differently to a successful vs. a failed login attempt, and a physics simulation needs to apply different rules if a particle hits a boundary or its energy exceeds a certain threshold.
The Language of Conditions: Booleans and Comparisons
At its heart, a computer's decision-making process is binary: a condition is either met or not met. In Python, these two states are represented by the Boolean values True and False. To create a condition, we use comparison operators to compare values. Since you have a strong background in mathematics, these operators should feel very familiar.
The primary comparison operators are:
==: Equal to!=: Not equal to<: Less than>: Greater than<=: Less than or equal to>=: Greater than or equal to
Notice the double equals sign == for testing equality. A single equals sign = is used for assigning a value to a variable, as you learned in our first lesson.
velocity = 343 # Speed of sound in m/s
is_supersonic = velocity > 343 # This condition is False
is_exactly_sonic = velocity == 343 # This condition is True
print(f"Is supersonic? {is_supersonic}")
print(f"Is exactly sonic? {is_exactly_sonic}")
The resource below, from a computational physics course, provides an excellent introduction to these concepts.
Tutorial, Part 3: Logicals, if blocks, and while loops
This article explains the foundational concepts of Boolean logic and comparison operators within a scientific programming context.
Please read the section "2. Logicals and logical variables." Focus on the part that introduces the Boolean values and comparison operators. Try the simple examples like 2 < 3 in your own Python console to see True and False in action.
The if Statement: Making a Decision
The simplest way to act on a condition is with an if statement. Its structure is straightforward: if a condition evaluates to True, the indented block of code directly below it is executed. If the condition is False, the block is skipped entirely.
The syntax requires a colon : at the end of the if line, and the code to be executed must be indented. This indentation is not just for readability; it is how Python defines a block of code.
temperature = 35 # degrees Celsius
if temperature > 30:
print("It's a hot day!")
print("This line will always execute, regardless of the temperature.")
The following video by Corey Schafer provides a very clear walkthrough of the basic if statement and the associated if-else structure.
Python Tutorial for Beginners 6: Conditionals and Booleans - If, Else, and Elif Statements
This video introduces the fundamental syntax and logic of conditional statements in Python.
Watch the first two minutes, covering the basic if statement and comparison operators. Notice how the code block only runs when the condition is True.
if-else: Providing an Alternative
An if statement on its own is useful, but often you want to do one thing if a condition is true, and something else if it is not. This is what the else statement is for. It provides an alternative code path that runs only when the if condition evaluates to False.
Here is a practical example you might see in ethical hacking when checking a server's response:
Let's expand our temperature example:
temperature = 15 # degrees Celsius
if temperature > 30:
print("It's a hot day!")
else:
print("It's not a hot day.")
The else statement guarantees that one of the two blocks will always be executed. The engaging video from NetworkChuck below demonstrates this if-else logic in a fun, security-themed context.
If Else Statements in Python // Python RIGHT NOW!! // EP 4
This video uses a memorable "evil Ben" scenario to explain how if and else create two distinct paths for a program to follow.
Watch the segment from this timestamp. Pay close attention to how the else statement fixes the "bipolar" logic of the initial if-only code, ensuring only one greeting is ever printed.
if-elif-else: Handling Multiple Conditions
What if you have more than two possibilities? For instance, in physics, a substance can be a solid, liquid, or gas depending on its temperature. You could use a series of if statements, but a more elegant solution is the elif statement, short for "else if".
The if-elif-else chain allows you to check multiple conditions in sequence.
- Python checks the
ifcondition first. If it'sTrue, its block is executed, and the rest of the chain is skipped. - If it's
False, it moves to the firstelifand checks its condition. If that'sTrue, its block is executed, and the rest is skipped. - This continues for any other
elifstatements. - If none of the
iforelifconditions are met, the finalelseblock is executed.
This structure is efficient because Python stops as soon as it finds a true condition.

# A simplified model for the state of water
temperature = 85 # degrees Celsius
if temperature <= 0:
print("Water is a solid (ice).")
elif temperature > 0 and temperature < 100:
print("Water is a liquid.")
else: # temperature >= 100
print("Water is a gas (steam).")
The Dataquest article below provides excellent written explanations and examples for the complete if-elif-else structure.
How to Use IF Statements in Python (if, else, elif, and more)
This tutorial walks through the conditional statements from the ground up, with clear code examples for each part.
Read the first three sections of the article: Basic if Statement else Statement elif Statement These sections will solidify your understanding of how the three keywords work together to build robust conditional logic.
Combining Conditions with and, or, and not
Often, a decision depends on more than one factor. For example, to log in, you need the correct username and the correct password. In a simulation, an event might trigger if a particle's position is within a certain range or its velocity exceeds a limit.
Python's logical operators let you build these complex conditions:
and:Trueonly if both conditions areTrue.or:Trueif at least one condition isTrue.not: Inverts a Boolean value (not TruebecomesFalse).
username = "admin"
password = "password123"
is_logged_in = False
if username == "admin" and password == "secret":
is_logged_in = True
print("Admin access granted.")
elif username == "guest" or password == "":
print("Guest access granted.")
else:
print("Access denied.")
The following section of the Dataquest article explains these operators very clearly and includes a helpful truth table.
How to Use IF Statements in Python (if, else, elif, and more)
This section explains how to build more complex conditions using logical operators.
Read the section on Multiple Conditions. Pay special attention to the examples using and and or, and study the truth table at the end of the section. It's a concise summary of how these operators work.
Practice: A Simple Access Control Script
Let's combine what you've learned in this lesson and the previous one. Write a Python script that does the following:
- Asks the user for their name.
- Asks the user for a password.
- If the name is "admin" and the password is "SuperSecretP@ss!", it should print a welcome message for the admin.
- If the name is "guest", it should print a limited access message, regardless of the password.
- In all other cases, it should print "Access Denied."
Once you've tried it yourself, you can model your solution on the logic presented in the videos and articles. This exercise is a small-scale version of the authentication checks used in many real-world applications.
Conclusion
In this lesson, you've acquired the fundamental tools for controlling your program's logic. You can now write code that responds and adapts to different situations.
- Key Takeaways:
- Conditional logic is built on Boolean values (
TrueandFalse) and comparison operators (==,!=,<,>). - The
if,elif, andelsestatements create pathways through your code, allowing it to make decisions. - Correct indentation is mandatory in Python for defining which code block belongs to which statement.
- Logical operators (
and,or,not) allow you to construct complex conditions by combining simpler ones.
- Conditional logic is built on Boolean values (
You've moved from writing simple, linear scripts to creating programs with branching logic. In our next lesson, we will add another crucial control structure: loops. While conditionals allow your program to choose which path to take, loops will allow it to repeat actions multiple times. This is essential for iterating through password lists in a hacking tool or advancing a physics simulation through time, step by step.