Part One: Overview of Program Control Structures
1.1 What is Control Flow
In programming, control flow refers to the order in which instructions are executed in a program. By default, a program executes line by line from top to bottom in the order the code is written, which is known as sequential structure. However, real-world problems often require different operations to be executed based on various conditions or the repetition of certain tasks, necessitating control structures to alter the program’s execution flow.
The three basic types of control structures are:
1. Sequential Structure – Code is executed in the order it is written
2. Conditional Structure – Different code branches are executed based on conditions
3. Loop Structure – A specific block of code is executed repeatedly
1.2 Why is Control Flow Necessary
Imagine the decision-making process in daily life:
· Conditional Judgment: If it rains, I will take an umbrella; otherwise, I will not take an umbrella
· Repetitive Loop: Every morning, I repeat the process of “getting up → brushing teeth → washing face → having breakfast”
In programming, control flow allows us to:
· Handle various situations
· Automate repetitive tasks
· Build complex logic and algorithms
· Create interactive programs
Part Two: Conditional Statements
2.1 Review of Boolean Logic
Before diving into conditional statements, let’s review Boolean logic, which is the foundation of conditional judgment:
“`python
# Boolean values: True and False
is_sunny = True
is_weekend = False
# Comparison operators (return Boolean values)
x = 10
y = 5
print(x > y) # True
print(x < y) # False
print(x == y) # False
print(x != y) # True
print(x >= y) # True
print(x <= y) # False
# Logical operators
a = True
b = False
print(a and b) # False – Returns True only if both are True
print(a or b) # True – Returns True if at least one is True
print(not a) # False – Negation
“`
2.2 Basics of the if Statement
The if statement is the most basic form of conditional judgment:
“`python
# Basic syntax
if condition:
# Execute this code if the condition is True
execute_statement
# Simple example
age = 18
if age >= 18:
print(“You are an adult, you can enter”)
“`
2.2.1 Code Blocks and Indentation
Python uses indentation to define code blocks, which is an important feature of Python:
“`python
# Correct indentation
if True:
print(“This line is inside the if statement”)
print(“This line is also inside the if statement”)
print(“This line is outside the if statement”) # This line is not inside the if statement
# Incorrect indentation will cause an error
if True:
print(“This will cause an error”) # IndentationError: expected an indented block
“`
Indentation rules:
· Use 4 spaces for one level of indentation (recommended)
· All statements in the same code block must have the same level of indentation
· Do not mix spaces and tabs
2.2.2 Conditional Expressions
Conditions can be various expressions as long as the final result is a Boolean value:
“`python
# Variable comparison
temperature = 25
if temperature > 30:
print(“It’s very hot”)
# Directly using Boolean variables
is_raining = True
if is_raining:
print(“Don’t forget to take an umbrella”)
# Complex conditional expressions
score = 85
attendance = 0.9
if score >= 60 and attendance >= 0.8:
print(“Passed the exam”)
# Using function calls as conditions
def is_even(number):
return number % 2 == 0
num = 10
if is_even(num):
print(f”{num} is even”)
“`
2.3 if-else Statement
When you need to perform other operations when the condition is not met, use the if-else statement:
“`python
# Basic syntax
if condition:
# Execute when the condition is True
statement_block1
else:
# Execute when the condition is False
statement_block2
# Example: Determine if a number is odd or even
number = 7
if number % 2 == 0:
print(f”{number} is even”)
else:
print(f”{number} is odd”)
# Example: Login validation
username = input(“Enter username: “)
password = input(“Enter password: “)
if username == “admin” and password == “123456”:
print(“Login successful!”)
else:
print(“Username or password is incorrect!”)
“`
2.4 if-elif-else Statement
When there are multiple conditions to check, use the if-elif-else statement:
“`python
# Basic syntax
if condition1:
# Execute when condition1 is True
statement_block1
elif condition2:
# Execute when condition2 is True
statement_block2
elif condition3:
# Execute when condition3 is True
statement_block3
else:
# Execute when none of the conditions are met
statement_block4
# Example: Determine grade level
score = 85
if score >= 90:
grade = “A”
print(“Excellent”)
elif score >= 80:
grade = “B”
print(“Good”)
elif score >= 70:
grade = “C”
print(“Average”)
elif score >= 60:
grade = “D”
print(“Pass”)
else:
grade = “F”
print(“Fail”)
print(f”Your grade level is: {grade}”)
“`
2.4.1 Execution Order of elif
The elif statements are checked in order, and once a condition is True, the corresponding code block is executed, skipping the remaining elif and else:
“`python
# Example: Understanding execution order
x = 15
if x > 10:
print(“x is greater than 10”) # This will be executed
elif x > 5:
print(“x is greater than 5”) # This will not execute because the previous condition is already satisfied
else:
print(“x is less than or equal to 5”) # This will also not execute
“`
2.5 Nested Conditional Statements
Conditional statements can contain other conditional statements inside them, which is called nested conditions:
“`python
# Example: Complex conditional judgment
age = 25
has_license = True
has_car = False
if age >= 18:
if has_license:
if has_car:
print(“You can drive”)
else:
print(“You have a license but no car, consider renting a car”)
else:
print(“You are an adult but do not have a license, cannot drive”)
else:
print(“You are underage, cannot drive”)
# Simplifying nested conditions using logical operators
if age >= 18 and has_license and has_car:
print(“You can drive”)
elif age >= 18 and has_license and not has_car:
print(“You have a license but no car, consider renting a car”)
elif age >= 18 and not has_license:
print(“You are an adult but do not have a license, cannot drive”)
else:
print(“You are underage, cannot drive”)
“`
2.6 Conditional Expressions (Ternary Operator)
For simple conditional assignments, you can use conditional expressions (also known as ternary operators):
“`python
# Traditional writing
x = 10
if x > 5:
result = “Greater than 5”
else:
result = “Less than or equal to 5”
# Using conditional expression (concise writing)
result = “Greater than 5” if x > 5 else “Less than or equal to 5”
print(result) # Output: Greater than 5
# More examples
age = 20
status = “Adult” if age >= 18 else “Minor”
print(f”Age {age} is {status}”)
# Nested conditional expressions (poor readability, not recommended for complex cases)
score = 85
grade = “A” if score >= 90 else “B” if score >= 80 else “C” if score >= 70 else “D” if score >= 60 else “F”
print(f”Score {score} corresponds to grade {grade}”)
“`
2.7 Practical Case: Smart Weather Suggestion System
“`python
“””
Smart Weather Suggestion System
Provides travel suggestions based on weather conditions
“””
print(“=== Smart Weather Suggestion System ===”)
# Get user input
temperature = float(input(“Enter current temperature (°C): “))
is_raining = input(“Is it raining? (yes/no): “).lower() == “yes”
wind_speed = float(input(“Enter wind speed (km/h): “))
is_weekend = input(“Is it the weekend? (yes/no): “).lower() == “yes”
print(“\n=== Weather Suggestions ===”)
# Temperature suggestions
if temperature > 30:
print(“🌞 It’s hot, suggestions:”)
print(” – Wear light clothing”)
print(” – Drink plenty of water to avoid heatstroke”)
print(” – Use sunscreen”)
elif temperature > 20:
print(“😊 The temperature is suitable, suggestions:”)
print(” – Wear casual clothes”)
print(” – Suitable for outdoor activities”)
elif temperature > 10:
print(“❄️ It’s cool, suggestions:”)
print(” – Wear long sleeves”)
print(” – You can add a light jacket”)
else:
print(“🥶 It’s cold, suggestions:”)
print(” – Wear thick clothes”)
print(” – Wear a scarf and gloves”)
print(” – Keep warm”)
# Rain suggestions
if is_raining:
print(“🌧️ On a rainy day, suggestions:”)
print(” – Bring an umbrella or raincoat”)
print(” – Choose non-slip shoes”)
print(” – Be careful of slippery roads”)
# Wind speed suggestions
if wind_speed > 50:
print(“💨 It’s very windy, suggestions:”)
print(” – Avoid staying under billboards or large trees”)
print(” – Be cautious of falling objects”)
elif wind_speed > 20:
print(“🍃 It’s windy, suggestions:”)
print(” – You can fly a kite”)
print(” – Be cautious of the wind”)
# Weekend activity suggestions
if is_weekend:
if not is_raining and temperature > 15:
print(“🎉 Good weather on the weekend, suggestions:”)
print(” – Go for a walk in the park”)
print(” – Organize outdoor sports”)
if temperature > 25:
print(” – You can go swimming”)
else:
print(“🏠 The weekend weather is average, suggestions:”)
print(” – Indoor activities”)
print(” – Watch a movie or read a book”)
“`
Part Three: Loop Statements
3.1 Concept of Loops
Loops allow us to execute a block of code multiple times, which is very useful for handling repetitive tasks. Python provides two main types of loop structures:
· for loop – Used for iterating over sequences or loops with a known number of iterations
· while loop – Used for condition-controlled loops
3.2 for Loop
The for loop is used to iterate over sequences (such as lists, strings, tuples, etc.) or other iterable objects:
“`python
# Basic syntax
for variable in sequence:
# Loop body
execute_statement
# Example: Iterate over a list
fruits = [“Apple”, “Banana”, “Orange”, “Grape”]
for fruit in fruits:
print(f”I like to eat {fruit}”)
# Output:
# I like to eat Apple
# I like to eat Banana
# I like to eat Orange
# I like to eat Grape
“`
3.2.1 range() Function
The range() function generates a sequence of numbers, commonly used to control the number of iterations in a loop:
“`python
# Basic usage of range() function
# range(stop) – from 0 to stop-1
# range(start, stop) – from start to stop-1
# range(start, stop, step) – from start to stop-1, with a step of step
# Example
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(2, 6))) # [2, 3, 4, 5]
print(list(range(1, 10, 2))) # [1, 3, 5, 7, 9]
# Using range() to control the number of iterations
for i in range(5):
print(f”This is the {i+1}th iteration”)
# Output:
# This is the 1th iteration
# This is the 2th iteration
# This is the 3th iteration
# This is the 4th iteration
# This is the 5th iteration
# Specifying starting value
for i in range(1, 6):
print(f”Number: {i}”)
# Using step
for i in range(0, 10, 2):
print(f”Even number: {i}”)
“`
3.2.2 Iterating Over Strings
Strings are also sequences and can be iterated over using a for loop:
“`python
# Iterate over each character in a string
text = “Python”
for char in text:
print(char)
# Output:
# P
# y
# t
# h
# o
# n
# Simultaneously get index and character
for index, char in enumerate(text):
print(f”The character at index {index} is {char}”)
# Output:
# The character at index 0 is P
# The character at index 1 is y
# The character at index 2 is t
# The character at index 3 is h
# The character at index 4 is o
# The character at index 5 is n
“`
3.2.3 Iterating Over Dictionaries
“`python
# Iterate over a dictionary
student = {
“Name”: “Xiao Ming”,
“Age”: 18,
“Class”: “Senior 3(1)”,
“Score”: 95
}
# Iterate over keys
for key in student:
print(f”Key: {key}”)
# Iterate over values
for value in student.values():
print(f”Value: {value}”)
# Iterate over key-value pairs
for key, value in student.items():
print(f”{key}: {value}”)
“`
3.3 while Loop
The while loop repeatedly executes a block of code as long as the condition is True:
“`python
# Basic syntax
while condition:
# Loop body
execute_statement
# Example: Counter
count = 1
while count <= 5:
print(f”Count: {count}”)
count += 1 # Important: Update the counter, otherwise it will loop infinitely
print(“Loop ended”)
# Output:
# Count: 1
# Count: 2
# Count: 3
# Count: 4
# Count: 5
# Loop ended
“`
3.3.1 Avoiding Infinite Loops
While loops can easily lead to infinite loops, ensure that the loop condition will eventually become False:
“`python
# Dangerous infinite loop example
# count = 1
# while count <= 5:
# print(f”Count: {count}”)
# # Forgetting to write count += 1 will lead to an infinite loop
# Correct approach: Ensure the condition changes
count = 1
while count <= 5:
print(f”Count: {count}”)
count += 1 # This line is important!
“`
3.3.2 Using break to Exit Loops
The break statement is used to immediately exit a loop:
“`python
# Example: Find the first number that meets the condition
numbers = [1, 3, 5, 8, 10, 13, 15]
for num in numbers:
if num % 2 == 0: # If it’s even
print(f”Found the first even number: {num}”)
break
print(f”Checking {num}, not even”)
print(“Search ended”)
# Output:
# Checking 1, not even
# Checking 3, not even
# Checking 5, not even
# Found the first even number: 8
# Search ended
“`
3.3.3 Using continue to Skip Current Iteration
The continue statement skips the remaining code in the current loop iteration and goes directly to the next iteration:
“`python
# Example: Only process odd numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num % 2 == 0: # If it’s even
continue # Skip even numbers
print(f”{num} is odd”)
# Output:
# 1 is odd
# 3 is odd
# 5 is odd
# 7 is odd
# 9 is odd
“`
3.4 else Clause in Loops
Python loops can have an else clause that executes when the loop completes normally (i.e., not exited via break):
“`python
# else clause in for loop
numbers = [2, 4, 6, 8, 10]
for num in numbers:
if num % 2 != 0: # If an odd number is found
print(“There is an odd number in the list”)
break
else:
print(“All numbers in the list are even”)
# Output: All numbers in the list are even
# Another example
primes = [2, 3, 5, 7, 11]
target = 4
for prime in primes:
if prime == target:
print(f”Found prime {target}”)
break
else:
print(f”Did not find prime {target}”)
# Output: Did not find prime 4
“`
3.5 Nested Loops
A loop can contain another loop inside it, which is called a nested loop:
“`python
# Example: Multiplication table
print(“=== Multiplication Table ===”)
for i in range(1, 4): # Outer loop
for j in range(1, 4): # Inner loop
product = i * j
print(f”{i} × {j} = {product}”, end=”\t”)
print() # New line
# Output:
# === Multiplication Table ===
# 1 × 1 = 1 1 × 2 = 2 1 × 3 = 3
# 2 × 1 = 2 2 × 2 = 4 2 × 3 = 6
# 3 × 1 = 3 3 × 2 = 6 3 × 3 = 9
# Example: 2D coordinates
print(“=== Coordinate Points ===”)
for x in range(3):
for y in range(2):
print(f”({x}, {y})”, end=” “)
print()
# Output:
# === Coordinate Points ===
# (0, 0) (0, 1)
# (1, 0) (1, 1)
# (2, 0) (2, 1)
“`
3.6 Loop Control Techniques
3.6.1 Using zip() to Iterate Over Multiple Sequences Simultaneously
“`python
# Iterate over multiple lists simultaneously
names = [“Xiao Ming”, “Xiao Hong”, “Xiao Gang”]
scores = [85, 92, 78]
subjects = [“Math”, “English”, “Chinese”]
for name, score, subject in zip(names, scores, subjects):
print(f”{name}’s score in {subject} is {score}”)
# Output:
# Xiao Ming’s score in Math is 85
# Xiao Hong’s score in English is 92
# Xiao Gang’s score in Chinese is 78
“`
3.6.2 Using enumerate() to Get Index
“`python
# Iterate over a list and get the index
fruits = [“Apple”, “Banana”, “Orange”, “Grape”]
for index, fruit in enumerate(fruits):
print(f”The {index}th fruit is {fruit}”)
# Output:
# The 0th fruit is Apple
# The 1th fruit is Banana
# The 2th fruit is Orange
# The 3th fruit is Grape
# Specifying starting index
for index, fruit in enumerate(fruits, start=1):
print(f”{index}. {fruit}”)
# Output:
# 1. Apple
# 2. Banana
# 3. Orange
# 4. Grape
“`
3.7 Practical Case: Number Guessing Game
“`python
“””
Number Guessing Game
The computer randomly generates a number, and the player tries to guess it
“””
import random
def guess_number_game():
print(“=== Number Guessing Game ===”)
print(“I have thought of a number between 1-100, try to guess it!”)
# Generate random number
secret_number = random.randint(1, 100)
attempts = 0
max_attempts = 7
print(f”You have {max_attempts} chances”)
while attempts < max_attempts:
# Get player input
try:
guess = int(input(f”\nAttempt {attempts + 1}, please enter a number: “))
except ValueError:
print(“Please enter a valid number!”)
continue
# Check guess result
if guess < 1 or guess > 100:
print(“Please enter a number between 1-100!”)
continue
attempts += 1
if guess == secret_number:
print(f”🎉 Congratulations! You guessed it! The number is {secret_number}”)
print(f”You guessed it in {attempts} attempts”)
break
elif guess < secret_number:
print(“📈 Guess too low, try a larger number”)
else:
print(“📉 Guess too high, try a smaller number”)
# Show remaining attempts
remaining = max_attempts – attempts
if remaining > 0:
print(f”You have {remaining} chances left”)
else:
print(f”\n💔 Game over! You did not guess the number”)
print(f”The correct answer is: {secret_number}”)
# Ask if they want to play again
play_again = input(“\nDo you want to play again? (yes/no): “).lower()
if play_again == “yes” or play_again == “y”:
guess_number_game()
else:
print(“Thank you for playing! Goodbye!”)
# Start the game
if __name__ == “__main__”:
guess_number_game()
“`
Part Four: Comprehensive Applications and Projects
4.1 Comprehensive Practice on Control Structures
4.1.1 Prime Number Judgment Program
“`python
“””
Prime Number Judgment Program
Determines whether the input number is a prime number
“””
def is_prime(number):
“””
Determines if a number is prime
Parameters:
number: The number to check
Returns:
bool: Returns True if prime, otherwise returns False
“””
if number < 2:
return False
elif number == 2:
return True
elif number % 2 == 0:
return False
# Check all odd numbers from 3 to sqrt(number)
import math
for i in range(3, int(math.sqrt(number)) + 1, 2):
if number % i == 0:
return False
return True
def prime_checker():
“””Prime Checker Main Function”””
print(“=== Prime Number Judgment Program ===”)
while True:
try:
num = int(input(“\nEnter a positive integer (enter 0 to exit): “))
except ValueError:
print(“Please enter a valid number!”)
continue
if num == 0:
print(“Program ended, goodbye!”)
break
if num < 0:
print(“Please enter a positive integer!”)
continue
if is_prime(num):
print(f”✅ {num} is a prime number”)
else:
print(f”❌ {num} is not a prime number”)
# Show all factors of the number
if num > 0:
factors = []
for i in range(1, num + 1):
if num % i == 0:
factors.append(i)
print(f”Factors of {num}: {factors}”)
# Run the program
prime_checker()
“`
4.1.2 Fibonacci Sequence Generator
“`python
“””
Fibonacci Sequence Generator
Generates a Fibonacci sequence of specified length
“””
def fibonacci_sequence(length):
“””
Generates a Fibonacci sequence
Parameters:
length: Length of the sequence
Returns:
list: List of Fibonacci sequence
“””
if length <= 0:
return []
elif length == 1:
return [0]
elif length == 2:
return [0, 1]
sequence = [0, 1]
for i in range(2, length):
next_number = sequence[i-1] + sequence[i-2]
sequence.append(next_number)
return sequence
def fibonacci_generator():
“””Fibonacci Sequence Generator Main Function”””
print(“=== Fibonacci Sequence Generator ===”)
while True:
try:
n = int(input(“\nHow long of a Fibonacci sequence to generate? (enter 0 to exit): “))
except ValueError:
print(“Please enter a valid number!”)
continue
if n == 0:
print(“Program ended, goodbye!”)
break
if n < 0:
print(“Please enter a non-negative integer!”)
continue
sequence = fibonacci_sequence(n)
if n == 0:
print(“Empty sequence”)
else:
print(f”The first {n} Fibonacci numbers: {sequence}”)
# Formatted output
print(“Formatted output:”)
for i, num in enumerate(sequence, 1):
print(f”Item {i}: {num}”)
# Run the program
fibonacci_generator()
“`
4.2 Comprehensive Project: Student Grade Management System
“`python
“””
Student Grade Management System
Implements functions for adding, querying, statistics, and analysis of student information
“””
# Global student list
students = []
def add_student():
“””Add student information”””
print(“\n— Add Student Information —“)
name = input(“Enter student name: “)
# Input validation: Name cannot be empty
if not name:
print(“Name cannot be empty!”)
return
# Check if name already exists
for student in students:
if student[“Name”] == name:
print(“This student already exists!”)
return
try:
chinese = float(input(“Enter Chinese score: “))
math = float(input(“Enter Math score: “))
english = float(input(“Enter English score: “))
except ValueError:
print(“Scores must be numbers!”)
return
# Score range validation
for score in [chinese, math, english]:
if score < 0 or score > 100:
print(“Scores must be between 0-100!”)
return
# Calculate total and average scores
total = chinese + math + english
average = total / 3
# Determine grade
if average >= 90:
grade = “A”
elif average >= 80:
grade = “B”
elif average >= 70:
grade = “C”
elif average >= 60:
grade = “D”
else:
grade = “F”
student = {
“Name”: name,
“Chinese”: chinese,
“Math”: math,
“English”: english,
“Total”: total,
“Average”: round(average, 2),
“Grade”: grade
}
students.append(student)
print(f”✅ Successfully added student: {name}”)
def show_all_students():
“””Show all student information”””
print(“\n— All Student Information —“)
if not students:
print(“No student information available”)
return
# Table header
print(f”{‘Name’:<10} {‘Chinese’:<6} {‘Math’:<6} {‘English’:<6} {‘Total’:<6} {‘Average’:<8} {‘Grade’:<6}”)
print(“-” * 60)
# Student information
for student in students:
print(f”{student[‘Name’]:<10} {student[‘Chinese’]:<6} {student[‘Math’]:<6} {student[‘English’]:<6} “
f”{student[‘Total’]:<6} {student[‘Average’]:<8} {student[‘Grade’]:<6}”)
def search_student():
“””Query student information”””
print(“\n— Query Student Information —“)
name = input(“Enter the name of the student to query: “)
found = False
for student in students:
if student[“Name”] == name:
print(“\nFound student information:”)
print(f”Name: {student[‘Name’]}”)
print(f”Chinese: {student[‘Chinese’]}”)
print(f”Math: {student[‘Math’]}”)
print(f”English: {student[‘English’]}”)
print(f”Total: {student[‘Total’]}”)
print(f”Average: {student[‘Average’]}”)
print(f”Grade: {student[‘Grade’]}”)
found = True
break
if not found:
print(f”❌ Student with name {name} not found”)
def calculate_statistics():
“””Calculate statistical information”””
print(“\n— Grade Statistics —“)
if not students:
print(“No student information available”)
return
# Total and average scores for each subject
subjects = [“Chinese”, “Math”, “English”]
stats = {}
for subject in subjects:
scores = [student[subject] for student in students]
stats[subject] = {
“Average”: sum(scores) / len(scores),
“Highest”: max(scores),
“Lowest”: min(scores),
“Passing Count”: len([s for s in scores if s >= 60])
}
# Display statistical results
for subject, data in stats.items():
print(f”\n{subject} subject:”)
print(f” Average: {data[‘Average’]:.2f}”)
print(f” Highest: {data[‘Highest’]}”)
print(f” Lowest: {data[‘Lowest’]}”)
print(f” Passing Count: {data[‘Passing Count’]}/{len(students)}”)
# Grade distribution
grade_distribution = {}
for student in students:
grade = student[“Grade”]
grade_distribution[grade] = grade_distribution.get(grade, 0) + 1
print(f”\nGrade Distribution:”)
for grade in sorted(grade_distribution.keys()):
count = grade_distribution[grade]
percentage = (count / len(students)) * 100
print(f” {grade} grade: {count} people ({percentage:.1f}%)”)
def main_menu():
“””Main Menu”””
while True:
print(“\n” + “=” * 50)
print(” Student Grade Management System”)
print(“=” * 50)
print(“1. Add Student Information”)
print(“2. Show All Students”)
print(“3. Query Student Information”)
print(“4. Grade Statistics”)
print(“5. Exit System”)
choice = input(“\nPlease select an operation (1-5): “)
if choice == “1”:
add_student()
elif choice == “2”:
show_all_students()
elif choice == “3”:
search_student()
elif choice == “4”:
calculate_statistics()
elif choice == “5”:
print(“Thank you for using the Student Grade Management System, goodbye!”)
break
else:
print(“Invalid choice, please re-enter!”)
# Start the system
if __name__ == “__main__”:
main_menu()
“`
Part Five: Debugging and Best Practices
5.1 Common Errors and Debugging
5.1.1 Common Errors in Conditional Statements
“`python
# Error 1: Using assignment operator = instead of comparison operator ==
x = 5
# if x = 10: # Syntax error
if x == 10: # Correct
print(“x equals 10”)
# Error 2: Forgetting the colon
# if x > 0 # Syntax error: missing colon
if x > 0: # Correct
print(“x is positive”)
# Error 3: Indentation error
# if x > 0:
# print(“x is positive”) # IndentationError
# Error 4: Logical error – incorrect condition order
score = 85
# Incorrect order
if score >= 60:
print(“Pass”)
elif score >= 80:
print(“Good”) # This will never execute
else:
print(“Fail”)
# Correct order
if score >= 80:
print(“Good”)
elif score >= 60:
print(“Pass”)
else:
print(“Fail”)
“`
5.1.2 Common Errors in Loops
“`python
# Error 1: Infinite loop
# count = 1
# while count <= 5: # Forgetting to update count, leading to infinite loop
# print(count)
# Correct writing
count = 1
while count <= 5:
print(count)
count += 1
# Error 2: Modifying a list being iterated over
# numbers = [1, 2, 3, 4, 5]
# for num in numbers:
# if num % 2 == 0:
# numbers.remove(num) # This will skip some elements
# Correct writing: Create a copy or use list comprehension
numbers = [1, 2, 3, 4, 5]
numbers = [num for num in numbers if num % 2 != 0] # Keep only odd numbers
“`
5.2 Debugging Techniques
5.2.1 Debugging with print Statements
“`python
def complex_calculation(numbers):
print(f”Debug: Input list = {numbers}”)
total = 0
count = 0
for i, num in enumerate(numbers):
print(f”Debug: Processing element {i} {num}”)
if num > 0:
total += num
count += 1
print(f”Debug: Updated total={total}, count={count}”)
else:
print(f”Debug: Skipping non-positive number {num}”)
if count > 0:
average = total / count
print(f”Debug: Calculating average {total}/{count} = {average}”)
return average
else:
print(“Debug: No positive numbers, returning 0”)
return 0
# Test
result = complex_calculation([5, -2, 8, 0, 3])
print(f”Final result: {result}”)
“`
5.2.2 Using Breakpoints and Debuggers
Set breakpoints in VS Code:
1. Click the blank area to the left of the line number to set a breakpoint (red dot)
2. Press F5 to start debugging
3. The program will pause at the breakpoint
4. You can view variable values, step through, etc.
5.3 Best Practices
1. Best Practices for Conditional Statements
· Keep conditions simple and clear
· Avoid deep nesting (generally no more than 3 levels)
· Use meaningful variable names
· Add comments to explain complex logic appropriately
2. Best Practices for Loops
· Choose the appropriate loop type (for for known iterations, while for condition control)
· Avoid unnecessary calculations inside loops
· Use break and continue timely to simplify logic
· Consider using list comprehensions to simplify simple loops
3. Code Readability
· Use blank lines to separate logical blocks
· Maintain consistent indentation style
· Write clear comments
· Use meaningful function and variable names
“`python
# Good code example
def calculate_grade(scores):
“””
Calculate grade distribution based on score list
Parameters:
scores: List of scores
Returns:
dict: Grade distribution dictionary
“””
if not scores:
return {}
grade_distribution = {
‘A’: 0, ‘B’: 0, ‘C’: 0, ‘D’: 0, ‘F’: 0
}
for score in scores:
# Validate score validity
if score < 0 or score > 100:
continue # Skip invalid scores
# Determine grade
if score >= 90:
grade = ‘A’
elif score >= 80:
grade = ‘B’
elif score >= 70:
grade = ‘C’
elif score >= 60:
grade = ‘D’
else:
grade = ‘F’
# Update distribution
grade_distribution[grade] += 1
return grade_distribution
# Usage example
test_scores = [85, 92, 78, 45, 67, 88, 95, 60, 72, 81]
distribution = calculate_grade(test_scores)
print(“Grade distribution:”)
for grade, count in distribution.items():
print(f”{grade} grade: {count} people”)
“`
Summary
Through this module, you have mastered:
1. Conditional statements: Usage and application scenarios of if, if-else, if-elif-else
2. Loop statements: Differences and usage of for loops and while loops
3. Loop control: Applications of break, continue, and else in loops
4. Nested structures: Writing techniques for nested conditions and loops
5. Practical functions: Usage of built-in functions like range(), enumerate(), zip()
6. Debugging techniques: Identifying and resolving common errors
7. Project practice: Reinforcing learned knowledge through complete projects
These control structures are the foundation of programming, and almost all programs will use them. Next, you will learn about functions and code reuse, which will help you write more modular and maintainable code.
Remember, improving programming skills requires a lot of practice. Write code frequently, try to solve different problems, and you will gradually master these concepts and be able to apply them flexibly.