【Python Primer】Control Your Program's Flow Freely! Thoroughly Master Conditional Branching with if Statements #4
Welcome back to our Python Primer series! In our previous lesson (#3), we learned about variables – how to store and label data. Now, let's take a giant leap forward and learn how to make our programs make decisions! So far, our code has run straight from top to bottom. But what if we want to do different things based on different situations? That's where conditional branching with if statements comes in.
Think of it like a choose-your-own-adventure book. Based on a choice or a condition, you turn to a different page and the story unfolds differently. Or, in everyday life: if it's raining, you take an umbrella; otherwise, you might take sunglasses. Python's if statements allow us to create these kinds of decision-making paths in our code.
In this post, we'll thoroughly master the if, elif, and else statements, learn about comparison operators, and see how to control the flow of our Python programs.
What is Conditional Branching? (Making Decisions in Code)
Conditional branching is all about telling your program to execute certain pieces of code only if a specific condition is met (is true). If the condition is not met (is false), the program might do something else, or nothing at all regarding that specific block.
Here are some everyday scenarios that translate well to programming logic:
- Logging in: If the entered password is correct, log the user in. Else, show an error message.
- Gaming: If the player's score is over 10,000 points, unlock a bonus level.
- Shopping: If an item is in stock, allow the user to add it to their cart. Else, display "Out of stock."
Python uses if statements to handle these kinds of decisions.
The Basic if Statement: Your First Decision
The simplest form of decision-making is the basic if statement. It checks a condition, and if that condition is true, it executes a block of code.
Syntax:
if condition:
# This code executes ONLY if the condition is True
# Notice the colon (:) at the end of the if line
# And VERY IMPORTANT: the indentation (spaces) at the beginning of this line!
statement_1
statement_2
The condition is an expression that Python evaluates to be either True or False. These True/False values are called Booleans. If the condition is True, the indented code block below the if statement is executed. If it's False, the indented code is skipped.
Comparison Operators: Building Your Conditions
To create meaningful conditions, we use comparison operators. These operators compare two values and return True or False.
==: Equal to (Are these two values the same?)
Careful!==(comparison) is different from=(assignment, used for variables).!=: Not equal to (Are these two values different?)>: Greater than<: Less than>=: Greater than or equal to<=: Less than or equal to
Simple Examples:
Let's try these in Python's interactive mode or in a script:
age = 20
if age >= 18:
print("You are considered an adult.")
temperature = 15
if temperature < 20:
print("It's a bit chilly, might need a jacket!")
# This message below will not print because the condition (10 > 20) is False
if 10 > 20:
print("This message will not appear.")
In the first example, age >= 18 (20 >= 18) is True, so "You are considered an adult." is printed. In the second, temperature < 20 (15 < 20) is True, so its message prints. The third condition is False, so its print statement is skipped.
Crucial Point: Indentation! In Python, the indentation (the spaces at the beginning of a line) is not just for looks—it's how Python knows which lines of code belong to the if statement (or other control structures). Usually, this means 4 spaces per indentation level.
What If the Condition is False? The else Clause
Sometimes, you want to do one thing if a condition is true, and a different thing if it's false. That's what the else clause is for.
Syntax:
if condition:
# This code executes if the condition is True
statement_A
else:
# This code executes if the condition is False
statement_B
Example:
user_input_password = "Python123"
correct_password = "P@sswOrd!23"
if user_input_password == correct_password:
print("Login successful! Welcome.")
else:
print("Incorrect password. Please try again.")
# Try changing user_input_password to match correct_password and see what happens!
In this case, since "Python123" is not equal to "P@sswOrd!23", the condition is False, and the code under the else block is executed.
Handling Multiple Conditions: The elif Clause
What if you have more than two possible paths? For instance, assigning a grade based on different score ranges. This is where elif (short for "else if") comes in handy. It lets you check multiple conditions in sequence.
Syntax:
if condition1:
# Executes if condition1 is True
statement_block_1
elif condition2:
# Executes if condition1 is False AND condition2 is True
statement_block_2
elif condition3:
# Executes if condition1 AND condition2 are False, AND condition3 is True
statement_block_3
else:
# Executes if ALL preceding conditions (condition1, condition2, condition3) are False
statement_block_default
Python checks the conditions from top to bottom. The first one that is True gets its code block executed, and then the rest of the if-elif-else structure is skipped. The final else is optional; it acts as a catch-all if none of the if or elif conditions were met.
Example: Grading based on score
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80: # This is checked only if score < 90
print("Grade: B")
elif score >= 70: # This is checked only if score < 80
print("Grade: C")
elif score >= 60: # This is checked only if score < 70
print("Grade: D")
else: # This executes if score < 60
print("Grade: F")
# Output for score = 85 will be: Grade: B
Since score is 85, the first condition (score >= 90) is false. The second condition (score >= 80) is true, so "Grade: B" is printed, and the remaining elif and else blocks are skipped.
A Little More on Conditions
Boolean Values (`True` / `False`)
As mentioned, conditions evaluate to Boolean values: True or False. You can also use these Boolean values directly in your if statements (often from variables that store a true/false state).
is_raining = True
has_umbrella = False
if is_raining:
print("It's raining!")
if has_umbrella:
print("Good thing you have an umbrella!")
else:
print("Oh no, you might get wet!")
# This is an example of a "nested" if statement - an if inside another if!
Combining Conditions (A Quick Peek)
You can also create more complex conditions using logical operators like and and or.
and: The combined condition isTrueonly if both individual conditions areTrue.age = 25 has_ticket = True if age >= 18 and has_ticket: print("Welcome to the event!") else: print("Sorry, you cannot enter.")or: The combined condition isTrueif at least one of the individual conditions isTrue.is_weekend = False is_holiday = True if is_weekend or is_holiday: print("Time to relax and enjoy!") else: print("Back to work/study.")
We'll explore these logical operators in more detail in a future lesson, but it's good to know they exist!
Don't Forget: Indentation is Key in Python!
It's worth repeating: Python uses indentation to define blocks of code. Unlike many other languages that use curly braces {}, Python relies on consistent spacing. If your indentation is wrong, your program will either not run (IndentationError) or not behave as you expect.
# Correct Indentation
if 10 > 5:
print("Correctly indented")
# Incorrect Indentation (this would cause an IndentationError)
# if 10 > 5:
# print("Incorrectly indented") # Missing indentation
Always use 4 spaces for each new level of indentation. Most code editors can be configured to insert 4 spaces when you press the Tab key.
You're Now a Decision Maker!
Congratulations! You've learned the fundamentals of conditional branching in Python using if, elif, and else. These statements are the core of how programs make decisions and respond intelligently to different inputs and situations.
Key takeaways:
- Use
ifto execute code based on a condition. - Use comparison operators (
==,!=,>,<,>=,<=) to form your conditions. - Add an
elseblock for code to run when theifcondition is false. - Use
elifto check multiple alternative conditions. - Indentation is absolutely crucial in Python!
Practice by writing small programs that make decisions. For example, a program that checks if a number is positive, negative, or zero. Or one that suggests an activity based on the day of the week.
Next up, we'll look at how to make our programs repeat actions using loops, which, combined with if statements, will unlock even more programming power!
コメント
コメントを投稿