Case Study Practical Exercises | 案例分析实战演练

📚 Case Study Practical Exercises | 案例分析实战演练

In computing, case studies are a powerful way to connect theory with real-world problem solving. By working through guided examples, you learn to apply computational thinking, design algorithms, write code, and evaluate solutions. This article presents three hands-on case studies suitable for Year 8 students following the AQA Computer Science curriculum: a number guessing game, a password strength checker, and a name-sorting program. Each case study will walk you through problem analysis, algorithm design, implementation, and testing, helping you build essential programming skills.

在计算机科学中,案例分析是将理论与实际解决问题相结合的强有力方式。通过完成引导式示例,你将学习应用计算思维、设计算法、编写代码和评估解决方案。本文针对遵循AQA计算机科学课程的八年级学生,提供了三个动手案例研究:猜数字游戏、密码强度检查器和姓名排序程序。每个案例都将带你完成问题分析、算法设计、实现和测试的流程,帮助你构建基本的编程技能。


1. Understanding Case Studies in Computing | 理解计算机案例分析

A case study in computing is a detailed examination of a real or simulated scenario that requires a computational solution. It helps you see how different concepts such as variables, conditions, loops, and functions work together to solve a problem. Instead of just memorising syntax, you learn to think like a programmer by breaking down a task into manageable parts.

计算机案例分析是对需要计算解决方案的真实或模拟场景的详细研究。它帮助你了解变量、条件、循环和函数等不同概念如何协同工作来解决问题。你无需死记硬背语法,而是通过将任务分解为可管理的部分来学会像程序员一样思考。


2. Case Study 1: The Number Guessing Game | 案例一:猜数字游戏

Our first case study is a classic beginner project: the number guessing game. The program randomly picks a number between 1 and 100, and the player must guess it. After each guess, the program gives a hint whether the guess is too high or too low. The game ends when the guess is correct, and the program displays the number of attempts taken.

我们的第一个案例是一个经典的初学者项目:猜数字游戏。程序随机选择一个1到100之间的数字,玩家必须猜出它。每次猜测后,程序会提示猜测是太高还是太低。当猜对时游戏结束,程序显示所花费的尝试次数。


3. Analysing the Game Problem | 分析游戏问题

Before writing any code, we must understand the problem clearly. The inputs are the player’s guesses (integers). The output is the hint and the final attempt count. The processing includes generating a random number, repeatedly asking for input, comparing the guess with the target, and keeping a counter. This is a classic example of a loop with conditional branching.

在编写任何代码之前,我们必须清楚地理解问题。输入是玩家的猜测(整数)。输出是提示和最终尝试次数。处理过程包括生成随机数、反复要求输入、将猜测与目标比较以及维护一个计数器。这是一个带有条件分支的循环的经典示例。


4. Designing the Algorithm | 设计算法

We can express the algorithm in simple steps. First, initialise the target number and the attempt counter. Then, start a loop that asks for a guess, increases the counter, and checks the guess. If the guess is lower than the target, output ‘Too low’. If higher, output ‘Too high’. If equal, output a congratulatory message and stop the loop. This structured plan makes coding straightforward.

我们可以用简单的步骤来表达算法。首先,初始化目标数字和尝试计数器。然后,开始一个循环:询问猜测,增加计数器,检查猜测。如果猜测低于目标,输出’太低’。如果高于,输出’太高’。如果相等,输出祝贺消息并停止循环。这个结构化的计划使编码变得简单明了。

Algorithm Steps: Set target = random(1,100); Set attempts = 0; Repeat: Input guess; attempts = attempts + 1; If guess < target Then print ‘Too low’; Else If guess > target Then print ‘Too high’; Until guess = target; Print ‘Correct! Attempts: ‘ + attempts

算法步骤: 设目标 = 随机(1,100); 设尝试次数 = 0; 重复: 输入猜测; 尝试次数 = 尝试次数 + 1; 如果 猜测 < 目标 则输出’太低’; 否则如果 猜测 > 目标 则输出 ‘太高’; 直到 猜测 = 目标; 输出 ‘正确!尝试次数:’ + 尝试次数


5. Coding the Game in Python | 用Python编写游戏

Translating the algorithm into Python is simple. We use the random module to generate the target, a while loop to keep asking until the correct guess, and if-elif-else statements for the hints. Below is the complete code. Notice how each line maps closely to the steps we designed.

将算法转换为Python很简单。我们使用random模块生成目标数字,用一个while循环持续询问直到猜对,并使用if-elif-else语句给出提示。以下是完整代码。请注意每一行如何与我们设计的步骤密切对应。

import random

target = random.randint(1, 100)
attempts = 0

while True:
    guess = int(input("Enter your guess (1-100): "))
    attempts += 1
    if guess < target:
        print("Too low! Try again.")
    elif guess > target:
        print("Too high! Try again.")
    else:
        print("Congratulations! You guessed it in", attempts, "attempts.")
        break

上述Python程序首先导入随机模块,设置目标数字和计数器。无限循环不断接受输入,并立即给予反馈。当猜测正确时,显示成功信息并退出循环。这体现了输入-处理-输出的基本模式。


6. Testing and Debugging | 测试与调试

Testing is an essential part of case studies. We need to check boundary values like 1 and 100, a typical middle guess, and what happens if the user enters a non-integer. In the code above, entering text would cause a crash. A robust program would include input validation. For now, we assume the user behaves and we run several test runs to confirm the hints work correctly.

测试是案例分析的重要部分。我们需要检查边界值,如1和100,一个典型的中间猜测,以及如果用户输入非整数会发生什么。在上面的代码中,输入文本会导致崩溃。一个健壮的程序应包含输入验证。目前,我们假设用户行为良好,并通过多次测试运行来确认提示工作正常。

  • Test 1: target = 50, guess = 25 → output ‘Too low’
  • Test 2: target = 50, guess = 75 → output ‘Too high’
  • Test 3: target = 50, guess = 50 → output ‘Congratulations… attempts: 1’
  • 测试1:目标=50,猜测=25 → 输出’太低’
  • 测试2:目标=50,猜测=75 → 输出’太高’
  • 测试3:目标=50,猜测=50 → 输出’恭喜… 尝试次数: 1′

7. Case Study 2: Building a Simple Password Strength Checker | 案例二:构建简单密码强度检查器

Many websites ask users to create passwords and often show a strength meter. We can design a simplified version that analyses a password and gives a rating such as ‘Weak’, ‘Medium’, or ‘Strong’. This case study focuses on string operations, conditional logic, and aggregation of multiple criteria.

许多网站在用户创建密码时会显示强度指示器。我们可以设计一个简化版本,分析密码并给出评级,如’弱’、’中’或’强’。此案例研究侧重于字符串操作、条件逻辑以及多个条件的综合评定。


8. Defining Password Strength Criteria | 定义密码强度标准

First, we list the criteria that influence password strength. A standard approach is to check length, presence of lowercase letters, uppercase letters, digits, and special characters. We will assign points for each characteristic. The table below shows the scoring rules we will use in our program.

首先,列出影响密码强度的条件。标准方法是检查长度、是否包含小写字母、大写字母、数字和特殊字符。我们将为每种特征分配分数。下表显示了程序中使用的评分规则。

Criteria Points Awarded
Length ≥ 8 1
Length ≥ 12 +1 (total 2)
Contains lowercase (a-z) 1
Contains uppercase (A-Z) 1
Contains digit (0-9) 1
Contains special char (e.g. !@#$) 1

Total points can range from 0 to 6. We define strength based on total: 0–2 points = Weak, 3–4 points = Medium, 5–6 points = Strong.

总分范围从0到6。我们根据总分定义强度:0–2分 = 弱,3–4分 = 中,5–6分 = 强。


9. Implementing the Strength Checker | 实现强度检查器

We can implement the checker in Python using string methods. We iterate over each character and use islower(), isupper(), and isdigit() to check categories. For special characters, we define a set. The score is accumulated, and the final rating is determined by comparing the total against thresholds.

我们可以使用Python的字符串方法来实现检查器。遍历每个字符,使用islower()isupper()isdigit()检查类别。对于特殊字符,我们定义一个集合。累计分数,通过将总分与阈值比较来确定最终评级。

def password_strength(password):
    score = 0
    if len(password) >= 8:
        score += 1
    if len(password) >= 12:
        score += 1

    has_lower = False
    has_upper = False
    has_digit = False
    has_special = False
    special_chars = "!@#$%^&*()-_=+[]{}|;:',.<>?/"

    for ch in password:
        if ch.islower():
            has_lower = True
        elif ch.isupper():
            has_upper = True
        elif ch.isdigit():
            has_digit = True
        elif ch in special_chars:
            has_special = True

    if has_lower: score += 1
    if has_upper: score += 1
    if has_digit: score += 1
    if has_special: score += 1

    if score <= 2:
        return "Weak"
    elif score <= 4:
        return "Medium"
    else:
        return "Strong"

该函数首先根据长度增加分数,然后检查是否存在四类字符,每发现一类加一分。最后,根据总分返回相应的强度字符串。注意我们使用了布尔标志来确保每种类型只加一次分。


10. Testing Different Passwords | 测试不同密码

We run the function with a variety of passwords to verify its behaviour. Testing is crucial to ensure the logic is sound and edge cases are handled. For example, an empty string should return ‘Weak’, and a long, mixed password should return ‘Strong’.

我们使用多种密码运行该函数以验证其行为。测试对于确保逻辑正确和处理边缘情况至关重要。例如,空字符串应返回’弱’,一个长的混合密码应返回’强’。

print(password_strength("abc"))       # Weak
print(password_strength("abcdefgh"))  # Weak (only length 8, no upper/digit/special)
print(password_strength("Abcd1234"))  # Medium (length, lower, upper, digit = 4)
print(password_strength("P@ssw0rd123!")) # Strong

测试输出显示’abc’得0分(弱),’abcdefgh’得1分(弱),’Abcd1234’得4分(中),而’P@ssw0rd123!’满足所有条件得6分(强)。这证实我们的强度检查器按预期工作。


11. Case Study 3: Sorting a List of Names | 案例三:姓名列表排序

Sorting data is a fundamental computing task. In this case study, we will implement the Bubble Sort algorithm to arrange a list of names in alphabetical order. Bubble Sort is simple and easy to understand, making it perfect for learning how sorting works at the logical level.

数据排序是一项基础的计算任务。在这个案例研究中,我们将实现冒泡排序算法,以字母顺序排列姓名列表。冒泡排序简单易懂,非常适合学习排序在逻辑层面是如何工作的。


12. Exploring Bubble Sort | 探索冒泡排序

Bubble Sort works by repeatedly stepping through the list, comparing adjacent elements and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, indicating the list is sorted. Larger elements ‘bubble’ to the end with each complete pass. The algorithm has a worst-case time complexity of O(n²) but is acceptable for small lists.

冒泡排序通过反复遍历列表、比较相邻元素并在顺序错误时交换它们来工作。重复遍历直到不需要交换,表示列表已排序。每完成一次完整遍历,较大的元素会’冒泡’到末尾。该算法最坏情况时间复杂度为O(n²),但对于小列表是可以接受的。

def bubble_sort_names(names):
    n = len(names)
    # Repeat n-1 times at most
    for i in range(n):
        swapped = False
        # Last i elements are already in place
        for j in range(0, n - i - 1):
            # Compare adjacent strings ignoring case
            if names[j].lower() > names[j+1].lower():
                # Swap if out of order
                names[j], names[j+1] = names[j+1], names[j]
                swapped = True
        # If no two elements were swapped, list is sorted
        if not swapped:
            break
    return names

# Test the function
test_names = ["Charlie", "alice", "Bob", "david"]
sorted_names = bubble_sort_names(test_names)
print(sorted_names)  # Output: ['alice', 'Bob', 'Charlie', 'david']

该Python函数使用了一个优化:如果在一轮遍历中没有发生交换,则提前退出。比较时我们将字符串转换为小写以确保不区分大小写的字母排序。注意列表是就地排序的,但为了清晰也返回了它。输出显示姓名已正确按字母顺序排列。

The three case studies demonstrated how to approach a problem by breaking it down, designing a solution, coding it, and testing it. These steps are the foundation of computational thinking. As you practise more case studies, you will become faster at recognising patterns and choosing the right constructs. Remember that making mistakes and debugging is part of the learning process.

这三个案例研究展示了如何通过分解问题、设计解决方案、编码和测试来处理问题。这些步骤是计算思维的基础。随着你练习更多的案例研究,你会更快地识别模式并选择正确的结构。记住,犯错误和调试是学习过程的一部分。

Published by TutorHao | Computer Science Revision Series | aleveler.com

更多咨询请联系16621398022(同微信)

Comments

屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from aleveler.com

Subscribe now to keep reading and get access to the full archive.

Continue reading