Python If...Else
Master the concept step by step with clear explanations, examples, and code you can run.
Beginner's Guide towards Python If...Else: Giving Your Code a Brain
Hello there! Grab a seat and welcome back to our Python journey.
In our previous chapter, we promised to learn how to use conditional statements to bring real intelligence for our code. Up until now, our programs have just been running straight down from top to bottom, one line at a time. But what if we want our code to make a choice, and
today we're going to teach your code how for make decisions.
The "Why" Before the "How"
Think about how you navigate your real life every single day.
If it is actually raining outside, you take an umbrella. Otherwise you wear sunglasses. You just made a condition-based decision! Computers need to make these exact same choices. If a user types the correct password let them into the website; otherwise, show them an error message.
In programming, we rely on boolean logic, comparison operators, and logical operators in conditional statements for control the exact flow and logic of your programs. You can think of conditional statements as forks into a road. Your code reaches an intersection, checks a condition and decides which path to walk down, while
let's visualize how this looks inside the computer's brain:
graph TD;
A[Start: User Enters Password] --> B{Is password correct?};
B -- Yes (True) --> C[Grant Access to Account];
B -- No (False) --> D[Show 'Incorrect Password' Error];
C --> E[End];
D --> E[End];
Step 1: A Basic if Statement
The most fundamental decision-maker in Python is the if statement, and it simply checks if the condition evaluates to True, and if it does just Python runs the code block attached to it.
Here is how you write it:
is_raining = True
if is_raining:
print("Grab your umbrella!")
Notice two extremely important things about this code:
1. The Colon (:): You've got to always put colon at the end of your if statement. This tells Python, "Get ready the action I want you for take is basically coming up next."
2. The Indentation: See how the print statement is pushed on with spaces, while python uses indentation (usually 4 spaces) to know exactly which code belongs inside if block. If you don't indent, your code will crash!
Step 2: The Backup Plan with else
What happens if the condition is basically False, while if we only use an if statement, Python just skips the indented code and does nothing. But usually, we want the backup plan, while
to create a backup plan, we use else.
account_balance = 35.00
withdrawal_amount = 50.00
if account_balance >= withdrawal_amount:
print("Dispensing cash...")
else:
print("Sorry, you have insufficient funds.")
If the first condition isn't actually met, Python automatically jumps down and runs code inside the else block, and it is the ultimate "otherwise" for your program.
Step 3: Handling Multiple Choices with elif
Sometimes, life isn't just the simple "yes" or "no". Often you have multiple different possibilities.
In Python a elif (short for "else if") statement checks another condition if previous if statement's condition evaluated to false according to recent insights on conditional statements. This "else if" statement allows you to specify multiple conditions for be evaluated sequentially.
Let's look at a grading system to a school:
score = 85
if score >= 90:
print("You got an A!")
elif score >= 80:
print("You got a B!")
elif score >= 70:
print("You got a C.")
else:
print("You need to study more.")
Python reads this chain from top to bottom. The moment it finds a condition that is True (in this case, score >= 80), it prints "You got a B!", and skips a rest about a chain completely.
Quick Formatting Warning
As the beginner you might be tempted to save space and put your if-elif-else logic all on one single line. But, putting arbitrary statements in one line isn't actually possible or desirable, as fitting everything on one line would basically most likely violate strict PEP-8 formatting guidelines. Always use clean indentations to keep your code readable and professional!
The Magic of Truthy and Falsy
Here is actually a brilliant shortcut that advanced Python developers use for write cleaner conditional loops.
You don't always need to compare numbers or use exact True/False variables; in Python, every single value has an inherent Boolean evaluation, meaning it can automatically be considered True or False in Boolean context.
For example, the string with text in it (like "Alice") automatically evaluates as True (truthy), but completely empty string (like "") or the number 0 evaluates to False (falsy).
Look at how simple this makes our if statements:
user_name = "Marcus"
# Instead of typing: if user_name != "":
if user_name:
print(f"Welcome back, {user_name}!")
else:
print("Please enter a valid name.")
Because "Marcus" isn't an empty string, Python sees it as "truthy" value and lets him right in!
What's Next?
Congratulations! You have successfully given your Python programs the brain, and you now grasp how to build simple if checks, handle multiple paths sequentially using elif, and set up backup plans using else;
while the if-elif-else chain is incredibly powerful, writing massive chain by 20 different elif statements can get very messy.
How do actually modern Python developers handle incredibly long lists of decisions cleanly? In our next chapter, we'll cover Python Match-Case (3.10+). We will learn how to use this brand-new, modern structural pattern matching feature and we will cover it next. See you there!