Practical Foundations for Future AI Developers
Control Flow Logic
Making Decisions in Code
Programs often need to make choices. Just like you might decide to take an umbrella if it looks like rain, a program can execute different actions based on specific conditions. This decision-making process is called control flow, and it's what makes code dynamic and responsive.
The simplest way to make a decision in Python is with an if statement. It checks if a condition is true, and if it is, the block of code underneath it runs. The code inside the if block must be indented, which is how Python knows it belongs to the condition.
age = 20
# This code will only run if the age is 18 or greater.
if age >= 18:
print("You are old enough to vote.")
print("This line runs no matter what.")
Building Conditions
The condition in an if statement is an expression that evaluates to either True or False. To build these expressions, you use comparison operators. They let you compare two values.
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | x == 10 |
!= | Not equal to | x != 10 |
> | Greater than | x > 5 |
< | Less than | x < 5 |
>= | Greater than or equal to | x >= 5 |
<= | Less than or equal to | x <= 5 |
What if you want to do something when the condition is not met? That's what else is for. An else statement provides a block of code that runs only when the if condition is False.
temperature = 15 # degrees Celsius
if temperature > 25:
print("It's a hot day!")
else:
print("It's not a hot day, bring a jacket.")
For situations with more than two possibilities, you can use elif, which is short for "else if." It lets you check multiple mutually exclusive conditions in a sequence. Python will check each condition from top to bottom and run the code for the first one that is True. If none are true, the else block runs.
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'D'
print(f"Your grade is {grade}") # Output: Your grade is B
Combining and Nesting Logic
Sometimes a single condition isn't enough. You might need to check if two things are true at once, or if at least one of several conditions is met. Logical operators allow you to combine boolean values (True or False) to create more complex checks.
| Operator | Description | Example |
|---|---|---|
and | Returns True if both conditions are true. | x > 5 and y < 10 |
or | Returns True if at least one condition is true. | x > 5 or y < 10 |
not | Inverts the boolean value. | not is_logged_in |
Here's how you can use them to validate data. This script checks that a user has entered a password and that it meets a minimum length.
password = "secret123"
username_provided = True
if username_provided and len(password) >= 8:
print("Login successful.")
else:
print("Login failed. Check username and password length.")
You can also place one conditional statement inside another. This is called nesting. It's useful for checking a secondary condition only after a primary one is met. However, try not to nest too deeply. Code that is heavily nested can become hard to read and understand, which goes against the Pythonic philosophy of clarity.
is_admin = True
file_exists = False
if is_admin:
print("Admin access granted.")
if file_exists:
print("Opening file...")
else:
print("Admin can create a new file.")
else:
print("Access denied.")
Python's Idea of Truth
In Python, conditional statements don't strictly require a True or False value. They can evaluate the "truthiness" of almost any value. This is a powerful shortcut.
Values that are considered "falsy" include:
- The number
0(and0.0) - An empty string
"" - An empty list
[], tuple(), or dictionary{} - The special value
None
Essentially, any non-empty data structure or non-zero number is considered "truthy."
This lets you write more concise code. Instead of checking if the length of a list is greater than zero, you can just check the list itself.
# Longer, less Pythonic way
user_list = []
if len(user_list) > 0:
print("List has users.")
else:
print("List is empty.")
# Shorter, more Pythonic way using truthiness
if user_list:
print("List has users.")
else:
print("List is empty.")
Understanding how to control the flow of your program is a huge step. It's the difference between a script that does one thing and a program that can react, adapt, and handle complex tasks intelligently.