Introduction to Python Programming: Understanding Control Flow with Ease
For programming beginners, the world of code seems filled with complex symbols and rules. But imagine writing a program as designing a set of action guidelines for a very obedient but opinionless robot. By default, this robot will strictly follow the guidelines in order, executing tasks step by step. However, in the real world, we often need to make different choices based on varying situations or repeat certain tasks.
This is where control flow comes into play. Control flow refers to the statements in programming languages that control the execution flow of a program, allowing our “robot” to make judgments under specific conditions or to repeat certain instructions, thus achieving more complex and intelligent tasks.
In Python, control flow is mainly divided into two categories: conditional statements and loop statements. Next, we will elaborate on each in detail.
1. Conditional Statements: Teaching the Program “If… Then…”
Conditional statements, as the name suggests, allow the program to decide what to do next based on the truth value of one or more conditions.
1. <span>if</span> Statement: The Most Basic Judgment
<span>if</span> statements are the simplest form of conditional judgment. The logic is: “If” a certain condition is true, execute the specified code block; if the condition is false, skip these codes.
Syntax Structure:
if condition:
# Code block executed when condition is true
# Note: The code here needs to be indented
- • Key Points:
- •
<span>if</span>is followed by a condition that can be evaluated as “true” (True) or “false” (False). - • The end of the condition must have a colon
<span>:</span>. - • The code block immediately following the
<span>if</span>statement must have the same indentation (usually 4 spaces), which is how Python recognizes the belonging of code blocks.
Code Example:
Assume we set a scenario where only users aged 18 and above can access a website.
age = 20
if age >= 18:
print("You are an adult, welcome to visit.")
# If the value of age is less than 18, the if condition will not be satisfied, and the print statement below will not be executed.
2. <span>if-else</span> Statement: Two Choices
<span>if</span> statements only handle the case when the condition is true, but what if we need to execute another plan when the condition is false? This is where the <span>if-else</span> statement comes in. Its logic is: “If” the condition is true, execute Plan A; “otherwise”, execute Plan B.
Syntax Structure:
if condition:
# Code block executed when condition is true
else:
# Code block executed when condition is false
Code Example:
Continuing from the previous example, we now want to give a clear prompt to underage users.
age = 16
if age >= 18:
print("You are an adult, welcome to visit.")
else:
print("Sorry, you are not an adult, access denied.")
In this example, because the value of <span>age</span> is 16, which does not satisfy the condition <span>>= 18</span>, the program will skip the code under <span>if</span> and execute the code under <span>else</span>.
3. <span>if-elif-else</span> Statement: Handling Multiple Possibilities
When we need to handle not just two situations, but multiple situations, we can use the <span>if-elif-else</span> structure. <span>elif</span> is short for “else if” and can be used multiple times in succession.
The logic is: the program will check each condition from top to bottom. Once it finds the first true condition and executes the corresponding code, the entire judgment will end. If all <span>if</span> and <span>elif</span> conditions are false, only then will the <span>else</span> part of the code be executed (<span>else</span> is optional).
Syntax Structure:
if condition1:
# Code block executed when condition1 is true
elif condition2:
# Code block executed when condition1 is false but condition2 is true
elif condition3:
# ...more conditions...
else:
# Code block executed when all conditions are false
Code Example:
Assume we need to evaluate grades based on exam scores: 90 and above is “Excellent”, 80-89 is “Good”, 60-79 is “Pass”, and below 60 is “Fail”.
score = 75
if score >= 90:
print("Rating: Excellent")
elif score >= 80:
print("Rating: Good")
elif score >= 60:
print("Rating: Pass")
else:
print("Rating: Fail")
# The output will be "Rating: Pass"
2. Loop Statements: Allowing the Program to Work Tirelessly
Loop statements allow a block of code to be executed multiple times, which is very useful when processing bulk data or tasks that need to be repeated. Python mainly has two types of loop statements: <span>for</span> loops and <span>while</span> loops.
1. <span>for</span> Loop: Knowing the Number of Repetitions
<span>for</span> loops are typically used to iterate over a sequence (such as a list, a string, or a range of numbers) and execute a code block for each element in the sequence. It is suitable for situations where we know in advance how many times to loop.
Syntax Structure:
for variable in sequence:
# Code block to execute for each element in the sequence
Code Example 1: Iterating Over a List
fruits = ["Apple", "Banana", "Orange"]
for fruit in fruits:
print("I like to eat: " + fruit)
This code will sequentially assign “Apple”, “Banana”, and “Orange” from the <span>fruits</span> list to the <span>fruit</span> variable and execute the <span>print</span> statement, ultimately outputting three lines of text.
Code Example 2: Using <span>range()</span> Function to Repeat a Fixed Number of Times
If we just want to repeat a block of code 5 times, we can use the <span>range()</span> function to generate a sequence of numbers.
for i in range(5): # range(5) generates a sequence of numbers from 0 to 4
print("This is the", i + 1, "time repeating.")
2. <span>while</span> Loop: Repeating Based on Conditions
<span>while</span> loops continuously execute a block of code as long as a certain condition remains true. It is suitable for situations where we do not know exactly how many times to loop, but we know under what conditions the loop should stop.
Syntax Structure:
while condition:
# Code block to repeat while condition is true
# Important: The code block usually needs statements that change the condition to avoid infinite loops
Code Example: A Simple Countdown Program
count = 3
while count > 0:
print("Countdown:", count)
count = count - 1 # Decrease count by 1 each loop, gradually approaching the condition of not satisfying the loop
print("Launch!")
In this example, as long as <span>count</span> is greater than 0, the loop will continue. When <span>count</span> decreases to 0, the condition <span>count > 0</span> will no longer be true, and the loop will end.
3. Loop Control Statements: Fine-tuning the Loop Process
Sometimes we do not want the loop to execute in a straightforward manner, but rather wish to end early or skip a particular execution under specific circumstances.
1. <span>break</span>: Immediately Terminate the Loop
<span>break</span> statements can be used to immediately exit the entire loop (whether it is a <span>for</span> or <span>while</span> loop), executing the code that follows the loop.
Code Example:
Searching for the first even number in a list of numbers, stopping the search once found.
numbers = [1, 3, 5, 4, 7, 9]
for num in numbers:
print("Checking number:", num)
if num % 2 == 0: # % is the modulus operator, even numbers divided by 2 have a remainder of 0
print("Found the first even number:", num)
break # After finding, immediately exit the for loop
2. <span>continue</span>: Skip the Current Loop
<span>continue</span> statements are used to end the current loop and directly start the next iteration.
Code Example:
Printing all odd numbers between 1 and 5.
for i in range(1, 6): # range(1, 6) generates 1, 2, 3, 4, 5
if i % 2 == 0: # If it is an even number
continue # Skip the remaining code in this loop (i.e., the print statement below)
print(i)
When <span>i</span> is an even number, the <span>continue</span> statement will cause the program to immediately return to the beginning of the <span>for</span> loop, starting the next iteration, thus skipping the step of printing even numbers.
Conclusion
Control flow is the cornerstone of programming. By effectively utilizing conditional judgments (<span>if</span>, <span>elif</span>, <span>else</span>) and loops (<span>for</span>, <span>while</span>), along with loop control statements (<span>break</span>, <span>continue</span>), you can build logically clear and powerful programs.
For beginners, the most important step is to write and run these example codes yourself and try modifying them to observe the changes in results. Through continuous practice, you will gradually master how to direct your program to make correct judgments and perform efficient repetitive tasks under your guidance.