Lesson 17: Programming Basics

1. Course Introduction

In the last class, we learned about variables, data types, user input, and conditional statements in Python, enabling us to write simple BMI calculators and grade evaluation programs. However, when faced with operations that need to be repeated, such as calculating the sum from 1 to 100, we would have to write a lot of repetitive code using our previous knowledge. Additionally, when we need to store multiple data points, such as recording the grades of 10 students in a class, using a single variable becomes impractical. In today’s lesson, we will learn the core concepts in Python that solve these problems—loop structures and container types (lists, dictionaries)—to make your programs more efficient and flexible.

2. Python Loop Structures: Automation Tools for Repeated Execution

Loop structures allow a program to execute a block of code repeatedly, avoiding redundancy. The most commonly used loops in Python are the for loop and the while loop, each suitable for different scenarios.

(1) For Loop: Fixed Number of Repetitions

The for loop is suitable for scenarios where the number of iterations is known, such as “print ‘Python’ 5 times” or “iterate through all numbers from 1 to 10”. The core concept is to control the number of iterations through an “iterable object” (such as a sequence of numbers generated by the range() function, strings, lists, etc.).

  1. Basic Format:
for variable in iterable_object:
    # Loop body (code executed in each iteration, must be indented by 4 spaces)

variable: In each iteration, an element is taken from the iterable object and assigned to this variable.iterable_object: An object that can yield elements one by one, such as a sequence of numbers generated by range(), strings, etc.

  1. Common Scenario 1: Iterating Through a Sequence of Numbers (Using range() Function)

The range() function is used to generate a continuous sequence of integers, with three usage forms:

Example 1: Calculate the sum from 1 to 10

sum_result = 0  # Initialize the sum variable to store the accumulated result
for i in range(1, 11):  # Iterate through all numbers from 1 to 10
    sum_result += i  # In each iteration, add i to sum_result
print("The sum from 1 to 10 is:", sum_result)  # Output: The sum from 1 to 10 is: 55

Example 2: Output even numbers from 1 to 10

print("Even numbers from 1 to 10:")
for num in range(2, 11, 2):  # Step of 2, iterating through 2, 4, 6, 8, 10
    print(num, end=" ")  # end=" " means no newline after output, separated by space
# Output: Even numbers from 1 to 10: 2 4 6 8 10

range(n): Generates integers from 0 to n-1 (e.g., range(5) generates 0, 1, 2, 3, 4).range(m, n): Generates integers from m to n-1 (e.g., range(2, 6) generates 2, 3, 4, 5).range(m, n, step): Generates integers from m to n-1 with a step of step (e.g., range(1, 10, 2) generates 1, 3, 5, 7, 9).

  1. Common Scenario 2: Iterating Through a String (Extracting Each Character)
message = "Python"
print("Each character in the string:")
for char in message:  # Extract each character from the string
    print(char)
# Output:
# Each character in the string:
# P
# y
# t
# h
# o
# n

(2) While Loop: Repetition Based on Condition

The while loop is suitable for scenarios where the number of iterations is unknown, only the loop condition is known, such as “prompt the user for a password until the correct one is entered” or “calculate until the accumulated sum exceeds 100”. The core concept is to control whether the loop continues through a “conditional expression”.

  1. Basic Format:
# Initialize variables (e.g., counter, accumulator)
while condition_expression:
    # Loop body (code executed when the condition is true, must be indented)
    # Update variables (to avoid infinite loops, e.g., increment counter, update accumulator)

Note: You must update variables in the loop body; otherwise, the condition will always be true, leading to an “infinite loop” (the program keeps executing repeatedly and cannot stop, requiring a forced shutdown).

  1. Example 1: Calculate until the accumulated sum exceeds 100
sum_num = 0
count = 1  # Counter, starting from 1
while sum_num <= 100:  # Condition: continue looping while the accumulated sum is less than or equal to 100
    sum_num += count
    count += 1  # Update the counter, increment by 1
print("When the accumulated sum exceeds 100, the total is:", sum_num)  # Output: When the accumulated sum exceeds 100, the total is: 105
print("The last number added is:", count - 1)  # Output: The last number added is: 14
  1. Example 2: Password Verification (Until Correct Input)
correct_password = "123456"  # Correct password
while True:  # Condition is True, enter the loop first
    user_input = input("Please enter the password:")
    if user_input == correct_password:
        print("Password correct, login successful!")
        break  # Exit the loop (stop when the condition is met)
    else:
        print("Incorrect password, please try again!")
# Running effect:
# Please enter the password: 123  →  Incorrect password, please try again!
# Please enter the password: 123456  →  Password correct, login successful!

break: Used to exit the current loop, regardless of whether the loop condition is met, executing break immediately ends the loop.

(3) Common Controls in Loops: break and continue

In addition to break, Python also provides continue to control loops. The differences are as follows:

  • break: Directly exits the entire loop, no further iterations are executed.
  • continue: Skips the remaining code in the current iteration and directly starts the next iteration.

Example: Output odd numbers from 1 to 10 (using continue to skip even numbers)

print("Odd numbers from 1 to 10:")
for num in range(1, 11):
    if num % 2 == 0:  # Check if it is an even number
        continue  # If it is even, skip the current iteration, do not execute the subsequent print
    print(num, end=" ")
# Output: Odd numbers from 1 to 10: 1 3 5 7 9

3. Python Container Types: “Toolbox” for Storing Multiple Data

When you need to store multiple data points (such as a class list of students or a list of product prices), a single variable cannot meet the needs. Python’s “container types” can efficiently store and manage multiple data points, with lists (list) and dictionaries (dict) being the most commonly used.

(1) List (list): Ordered “Data Queue”

A list is the most commonly used container in Python, used to store ordered and mutable multiple data points, where data types can differ (e.g., storing strings, integers, and floats simultaneously), represented by square brackets []. Elements are separated by commas.

  1. Creating and Accessing Lists

Create a list: list_name = [element1, element2, element3, …]

# Example: Create a list to store student names
students = ["Xiao Ming", "Xiao Hong", "Xiao Gang", "Xiao Li"]
# Example: Create a list to store mixed type data
mix_list = ["Python", 2025, 92.5, True]

Accessing list elements: Access through “index” (the position number of the element in the list), with indexing starting from 0 (the first element has index 0, the second has index 1, and so on), format: list_name[index]

print(students[0])  # Output the first element: Xiao Ming
print(students[2])  # Output the third element: Xiao Gang
# Reverse access: index -1 indicates the last element, -2 indicates the second to last
print(students[-1])  # Output the last element: Xiao Li

Accessing the length of a list: Use the len() function to get the number of elements in the list: len(list_name)

print(len(students))  # Output: 4 (the students list has 4 elements)
  1. Common List Operations (Add, Delete, Modify, Query)

Add an element (append to the end of the list): list_name.append(new_element)

students.append("Xiao Liang")  # Add new element "Xiao Liang" to the students list
print(students)  # Output: ["Xiao Ming", "Xiao Hong", "Xiao Gang", "Xiao Li", "Xiao Liang"]

Modify an element (modify by index): list_name[index] = new_value

students[1] = "Xiao Mei"  # Change the element at index 1 from "Xiao Hong" to "Xiao Mei"
print(students)  # Output: ["Xiao Ming", "Xiao Mei", "Xiao Gang", "Xiao Li", "Xiao Liang"]

Delete an element (delete by index): del list_name[index] or list_name.pop(index) (pop() will return the deleted element)

del students[3]  # Delete the element at index 3 "Xiao Li"
print(students)  # Output: ["Xiao Ming", "Xiao Mei", "Xiao Gang", "Xiao Liang"]
removed_student = students.pop(2)  # Delete the element at index 2 "Xiao Gang" and return that element
print("Removed student:", removed_student)  # Output: Removed student: Xiao Gang
print(students)  # Output: ["Xiao Ming", "Xiao Mei", "Xiao Liang"]

Finding an element (check if an element is in the list): element in list_name (returns boolean True/False)

print("Xiao Mei" in students)  # Output: True ("Xiao Mei" is in the list)
print("Xiao Gang" in students)  # Output: False ("Xiao Gang" has been deleted)
  1. Iterating Through a List (Using for Loop)

Use a for loop to extract each element from the list without focusing on the index:

# Example: Iterate through the student list and output each student's name
students = ["Xiao Ming", "Xiao Mei", "Xiao Liang"]
print("Class student list:")
for student in students:
    print("- " + student)
# Output:
# Class student list:
# - Xiao Ming
# - Xiao Mei
# - Xiao Liang

(2) Dictionary (dict): Key-Value Corresponding “Data Dictionary”

When you need to store data corresponding to “key-value” pairs (such as student names and grades, product names and prices), dictionaries are more efficient than lists, represented by curly braces {}. Each element is a “key: value” pair, where the key (key) is unique and unmodifiable, while the value (value) is modifiable and can be of any type.

  1. Creating and Accessing Dictionaries

Create a dictionary: dict_name = {key1: value1, key2: value2, key3: value3, …}

# Example: Create a dictionary for student names and grades
student_scores = {"Xiao Ming": 95, "Xiao Mei": 88, "Xiao Liang": 92}
# Example: Create a dictionary for products and prices (values are floats)
product_prices = {"Apple": 5.9, "Banana": 3.5, "Orange": 4.2}

Accessing values in a dictionary: Access through “key”, format: dict_name[key] (if the key does not exist, an error will occur)

print(student_scores["Xiao Mei"])  # Output: 88 (get the score corresponding to "Xiao Mei")
print(product_prices["Apple"])  # Output: 5.9 (get the price corresponding to "Apple")
# Safe access: Use the get() method, which returns a default value if the key does not exist (avoiding errors)
print(student_scores.get("Xiao Gang", 0))  # Output: 0 ("Xiao Gang" does not exist, returns default value 0)

Getting keys/values/key-value pairs from a dictionary:

print(student_scores.keys())  # Output all keys: dict_keys(['Xiao Ming', 'Xiao Mei', 'Xiao Liang'])
print(student_scores.values())  # Output all values: dict_values([95, 88, 92])
print(student_scores.items())  # Output all key-value pairs: dict_items([('Xiao Ming', 95), ('Xiao Mei', 88), ('Xiao Liang', 92)])
  1. Common Dictionary Operations (Add, Delete, Modify, Query)

Add a key-value pair (when the key does not exist): dict_name[new_key] = new_value

student_scores["Xiao Li"] = 85  # Add the key-value pair "Xiao Li: 85"
print(student_scores)  # Output: {"Xiao Ming": 95, "Xiao Mei": 88, "Xiao Liang": 92, "Xiao Li": 85}

Modify a value (when the key exists): dict_name[existing_key] = new_value

student_scores["Xiao Liang"] = 94  # Change "Xiao Liang"'s score from 92 to 94
print(student_scores)  # Output: {"Xiao Ming": 95, "Xiao Mei": 88, "Xiao Liang": 94, "Xiao Li": 85}

Delete a key-value pair: del dict_name[key] or dict_name.pop(key)

del student_scores["Xiao Li"]  # Delete the key-value pair "Xiao Li: 85"
print(student_scores)  # Output: {"Xiao Ming": 95, "Xiao Mei": 88, "Xiao Liang": 94}

Finding a key (check if a key is in the dictionary): key in dict_name (returns boolean)

print("Xiao Mei" in student_scores)  # Output: True ("Xiao Mei" is a key in the dictionary)
print("88" in student_scores)  # Output: False (88 is a value, not a key)
  1. Iterating Through a Dictionary (Using for Loop)

Common two ways to iterate: iterate through all keys, iterate through all key-value pairs:

# Method 1: Iterate through all keys, then get values through keys
print("Student Score Table (Method 1):")
for name in student_scores.keys():
    print(name + "'s score:" + str(student_scores[name]))
# Method 2: Directly iterate through all key-value pairs (using items() method)
print("\nStudent Score Table (Method 2):")
for name, score in student_scores.items():
    print(f"{name}'s score: {score}")  # f-string formatted string, more concise
# Output:
# Student Score Table (Method 1):
# Xiao Ming's score: 95
# Xiao Mei's score: 88
# Xiao Liang's score: 94
#
# Student Score Table (Method 2):
# Xiao Ming's score: 95
# Xiao Mei's score: 88
# Xiao Liang's score: 94

4. Practical Case: Comprehensive Use of Loops and Containers

Combining the knowledge of loops and containers learned in this lesson, write a “Class Grade Management Program” to achieve the following functions: 1. Enter the names and grades of 3 students; 2. Calculate the average score of the class; 3. Output the list of students with grades greater than or equal to 90.

(1) Requirement Analysis and Thought Process

  1. Use a dictionary to store student names and grades (key: name, value: grade).
  1. Use a for loop to iterate 3 times, each time using input() to get the student’s name and grade, storing them in the dictionary.
  1. Use the sum() function to calculate the total of all grades in the dictionary, combined with the len() function to calculate the average score.
  1. Use a for loop to iterate through the dictionary, filtering out students with grades ≥ 90 and outputting their names.

(2) Complete Code and Explanation

# Step 1: Initialize an empty dictionary to store student grades
student_dict = {}
# Step 2: Enter the names and grades of 3 students (for loop 3 times)
for i in range(3):
    name = input(f"Please enter the name of student {i+1}:")  # f-string dynamically shows the number
    score = int(input(f"Please enter {name}'s grade:"))  # Convert to integer
    student_dict[name] = score  # Store name and grade in the dictionary
# Step 3: Calculate the average score of the class
total_score = sum(student_dict.values())  # sum() calculates the total score
student_count = len(student_dict)  # len() calculates the number of students
average_score = total_score / student_count  # Calculate the average score
print(f"\nClass average score: {average_score:.1f} points")  # Output with 1 decimal place
# Step 4: Filter and output students with grades ≥ 90
print("\nStudents with grades greater than or equal to 90:")
high_score_students = []  # Use a list to store high-scoring students' names
for name, score in student_dict.items():
    if score >= 90:
        high_score_students.append(name)
        print(f"- {name}: {score} points")
# If there are no high-scoring students, give a prompt
if len(high_score_students) == 0:
    print("- No students with grades greater than or equal to 90")

(3) Running Test

  1. Run the program and sequentially input the information of 3 students (e.g., Xiao Ming 95, Xiao Mei 88, Xiao Liang 92).
  1. The program outputs:
Class average score: 91.7 points
Students with grades greater than or equal to 90:
- Xiao Ming: 95 points
- Xiao Liang: 92 points
  1. If the input student grades are all below 90 (e.g., Xiao Hong 85, Xiao Gang 82, Xiao Li 88), the program outputs:
Class average score: 85.0 points
Students with grades greater than or equal to 90:
- No students with grades greater than or equal to 90

5. Class Summary

(1) Class Summary

  1. Loop structures: The for loop is suitable for known repetitions (e.g., iterating through sequences), while the while loop is suitable for unknown repetitions based on conditions (e.g., password verification). break exits the loop, and continue skips the current iteration.
  1. Container types: Lists (list) are ordered and mutable “data queues”, accessed by index, suitable for storing ordered data; dictionaries (dict) are key-value corresponding “data dictionaries”, accessed by key, suitable for storing associated data.
  1. Comprehensive use: Combining loops and containers can efficiently handle multiple data scenarios, such as iterating through lists to calculate totals or iterating through dictionaries to filter data.

Leave a Comment