Skip to content

Fundamentals of Computer Programming: In-Class Quiz (Paper B) — Questions and Reference Solutions

Updated: 2026-10-25 23:01 · English
Table of contents (13)

Language / 语言: English | 中文版

Southwestern University of Finance and Economics | Instructor: Luping Zhang | Date: October 21, 2026 | Paper Type: Paper B (SWUFE-20261021-QUIZ1-B)

Instructions:

  1. Clearly enter your name and student ID and select your session in the information table on the first page.
  2. When designing programs, choose appropriate variables, control flow, and functions for the scenario (identify and design independent system units). Follow the naming and data type annotation conventions taught in class. More than one solution is acceptable; marks are awarded for the soundness and appropriateness of the design.
  3. Write each answer in the corresponding area of the answer sheet. Keep code indentation clear and consistent with Python syntax.
  4. You may answer in Chinese or English.

[Q1] Question 1

Problem Statement

Read the following Python code:

python
def calc_settlement(amount: float) -> float:
    fee = 15.0
    if amount >= 200.0:
        fee = 0.0
    return amount + fee

order_amount = 260.0
total = calc_settlement(order_amount)
print(total)

Using the code above and what you have learned, answer the following questions:

  • [Q1.1] Explain each step in Python's execution of this code and the associated memory model. You do not need to explain the memory model for the function declaration.
  • [Q1.2] Explain the concept, structure, and key characteristics of code blocks, and give examples of common code blocks.

Reference Solution for [Q1.1]

1. Overview of the Python Memory Model

In our course model, Python manages variables and data in memory using two components: a variable table, which records the variable names defined in the program (with a separate local variable table created when a function runs), and data storage units, which store the actual data values (such as 260.0, 15.0, and 0.0).

A variable in the variable table and its value in a data storage unit are bound together through a memory address. When Python executes an assignment statement (variable = expression), it first evaluates the expression on the right-hand side, stores the resulting value in a data storage unit, and binds that value to the variable on the left-hand side. When an existing variable is reassigned, Python stores the new value in a separate data storage unit and rebinds the new value to the variable.


2. Step-by-Step Execution

  1. Lines 1–5 (def calc_settlement(amount: float) -> float: ..., Function Definition):

    • Python records the definition of calc_settlement. The indented function body (Lines 2–5) does not execute at this stage.
  2. Line 7 (order_amount = 260.0, Initial Assignment):

    • Python evaluates the right-hand side 260.0, stores 260.0 in a data storage unit, and binds the value 260.0 to the variable order_amount.
  3. Line 8 (total = calc_settlement(order_amount), Function Call and Execution):

    • Python first evaluates the right-hand side calc_settlement(order_amount) by reading the value bound to order_amount (260.0) and calling calc_settlement:
      • Parameter Binding (Line 1): Inside the function's local scope, Python binds the passed value 260.0 to the local parameter amount.
      • Line 2 (fee = 15.0, Local Assignment): Python evaluates 15.0, stores 15.0 in a data storage unit, and binds 15.0 to the local variable fee.
      • Line 3 (if amount >= 200.0:, Condition Evaluation): Python reads the value bound to amount (260.0) and evaluates 260.0 >= 200.0. Because the condition is True, execution enters the indented body of the if block on Line 4.
      • Line 4 ( fee = 0.0, Reassignment): Python evaluates 0.0, stores 0.0 in a new data storage unit, and rebinds the new value 0.0 to the local variable fee (replacing its previous binding to 15.0).
      • Line 5 (return amount + fee, Return Value): Execution exits the if block and evaluates amount + fee (260.0 + 0.0 = 260.0). The function returns 260.0 to the call site on Line 8 and terminates (destroying its local variables amount and fee).
    • Binding Return Result (Line 8): Back in the main flow, Python stores the returned value 260.0 in a data storage unit and binds 260.0 to the variable total.
  4. Line 9 (print(total), Screen Output):

    • Python reads the value bound to total (260.0) and prints 260.0 to the terminal.
    • Terminal Output:
      text
      260.0
      

3. Memory Model Diagram

text
+-------------------------------------------------------------------+
|                     MEMORY MODEL ILLUSTRATION                     |
|      (Variables and values are bound via memory addresses)        |
+-------------------------------+-----------------------------------+
|         VARIABLE TABLE        |        DATA STORAGE UNITS         |
+-------------------------------+-----------------------------------+
| [Main Scope]                  |                                   |
|   order_amount ---------------------->  [ 260.0 ]  (Line 7)       |
|                               |                                   |
|   total        ---------------------->  [ 260.0 ]  (Line 8)       |
+-------------------------------+-----------------------------------+
| [Local Scope: calc_settlement]|                                   |
|   amount       ---------------------->  [ 260.0 ]  (Line 1)       |
|                               |                                   |
|   fee          -------x-------------->  [  15.0 ]  (Line 2)       |
|                   |           |                                   |
|                   +------------------>  [   0.0 ]  (Line 4)       |
|                  (Rebound)    |                                   |
+-------------------------------+-----------------------------------+

Reference Solution for [Q1.2]

1. Concept of a Code Block

In Python, a code block is a self-contained logical structure composed of a header line and an indented body; it organizes and governs a group of statements as a single execution unit.

2. Structure of a Code Block

A code block has a fixed two-part structure (Header + Body):

text
keyword_header_statement:          # Part 1: Header (ends with a colon ':')
    body_statement_1               # Part 2: Body (indented by 4 spaces)
    body_statement_2               # Part 2: Body (aligned at 4 spaces)
    ...

subsequent_statement               # Outside the code block (indentation restored)
  1. Header Line: The header starts with a keyword (such as if, elif, else, def, for, or while), states the control condition or definition rule, and ends with a colon (:).
  2. Body: The body immediately follows the header and consists of one or more indented statements (4 spaces per indentation level). Returning to the header's indentation level on a subsequent line ends the code block.

3. Key Characteristics

  1. Fixed and Indivisible Structure: A code block has a fixed syntactic form (header + indented body) and acts as a single structural whole: its parts must appear together or not at all, and neither part can stand alone.
  2. Unified Execution as a Whole: A code block forms a single execution unit; its statements either execute together in sequence or are skipped together as a whole.
  3. Indentation-Defined Boundaries: Python uses indentation to group statements. All statements at the same logical level in the body must share the same indentation, and restoring the header's indentation level exits the block.
  4. Hierarchical Nesting: Because a code block is a self-contained unit, an entire inner code block (header + body) can be placed inside the body of an outer code block using deeper indentation.

4. Examples of Code Blocks

  1. Conditional Branch Code Block (if / elif / else):
    python
    if amount >= 200.0:                  # Header
        fee = 0.0                        # Body
    
  2. Function Definition Code Block (def):
    python
    def calculate_subtotal(unit_price: float, quantity: int) -> float:  # Header
        return unit_price * quantity                                    # Body
    
  3. Loop Code Block (for / while):
    python
    for vehicle_id in [5, 2, 7]:         # Header
        print(vehicle_id)                # Body
    

[Q2] Question 2

Problem Statement

A module of a corporate finance system handles expense settlement for three types of business travel: routine visits, off-site training, and on-site project work. All three types use the same accommodation reimbursement rules: the accommodation reimbursement limit is the number of travel days multiplied by CNY 400 per day; if the invoiced accommodation amount exceeds this limit, only the limit is reimbursed; otherwise, the invoiced amount is reimbursed.

The total reimbursable amount for each travel claim is the sum of the approved accommodation reimbursement and the transportation allowance. Table 1 lists the transportation allowances. Table 2 gives the details of three travel claims awaiting settlement.

Table 1: Transportation Allowances

Trip type Allowance (CNY/trip)
Routine visits 200
Off-site training 300
On-site project work 500

Table 2: Travel Claims Awaiting Settlement

Trip type Days Invoiced accommodation (CNY)
Routine visits 2 700
Off-site training 3 1200
On-site project work 4 1800
  • [Q2.1] For the scenario above, divide the travel expense settlement system into appropriate functions and write the corresponding Python code. Call your functions to calculate and output the total reimbursable amount for each of the three travel claims in Table 2.
  • [Q2.2] Draw a system structure diagram for your program using the "system" model introduced in the lecture notes.

Reference Solution 1 for [Q2.1] (Two-Stage Pipeline: 2 Functions)

1. Functional Division

The travel expense settlement calculation can be divided into two functions (systems), where the output of the first function is an input to the second:

  1. cal_approved_accommodation(days: int, invoiced_amount: float) -> float: Takes the travel days and invoiced_amount, computes the accommodation reimbursement limit (days * 400.0), and returns the smaller of the invoiced amount and the limit (approved_accommodation).
  2. cal_total_reimbursement(approved_accommodation: float, trip_type: str) -> float: Takes approved_accommodation (the output of cal_approved_accommodation) and trip_type, selects the corresponding transportation allowance, and returns the total reimbursable amount (approved_accommodation + allowance).

2. Python Code

python
# Function 1: Calculate approved accommodation reimbursement from days and invoiced amount
def cal_approved_accommodation(days: int, invoiced_amount: float) -> float:
    limit = days * 400.0
    if invoiced_amount > limit:
        approved_accommodation = limit
    else:
        approved_accommodation = invoiced_amount
    return approved_accommodation


# Function 2: Calculate total reimbursable amount from approved accommodation and trip type
def cal_total_reimbursement(approved_accommodation: float, trip_type: str) -> float:
    if trip_type == "Routine visits":
        allowance = 200.0
    elif trip_type == "Off-site training":
        allowance = 300.0
    elif trip_type == "On-site project work":
        allowance = 500.0
    else:
        print("Trip type is incorrect!")
        return -1.0 # An exception indicator
    total_reimbursement = approved_accommodation + allowance
    return total_reimbursement


# Calculate and output total reimbursable amounts for the three claims in Table 2
acc_visit = cal_approved_accommodation(2, 700.0)
total_visit = cal_total_reimbursement(acc_visit, "Routine visits")
print(f"Routine visits total reimbursement: {total_visit:.2f} CNY")

acc_training = cal_approved_accommodation(3, 1200.0)
total_training = cal_total_reimbursement(acc_training, "Off-site training")
print(f"Off-site training total reimbursement: {total_training:.2f} CNY")

acc_project = cal_approved_accommodation(4, 1800.0)
total_project = cal_total_reimbursement(acc_project, "On-site project work")
print(f"On-site project work total reimbursement: {total_project:.2f} CNY")

Reference Solution 1 for [Q2.2]

Each function is an Input-Process-Output (IPO) system, and the output of System 1 (approved_accommodation) passes directly to System 2 as an input:

System Structure Diagram: Travel Expense Settlement (IPO Model)


Reference Solution 2 for [Q2.1] (1 Helper Function + 3 Business Functions)

1. Functional Division

The calculation can also be divided into one helper function and three business functions:

  1. Helper Function (cal_approved_accommodation): Takes days and invoiced_amount, computes the accommodation limit (days * 400.0), and returns the smaller of the invoiced amount and the limit (approved_accommodation).
  2. Business Functions (cal_visit_reimbursement, cal_training_reimbursement, and cal_project_reimbursement): Each function takes days and invoiced_amount, calls cal_approved_accommodation(days, invoiced_amount), and adds the transportation allowance for that trip type (200.0, 300.0, or 500.0, respectively).

2. Python Code

python
# Helper function: Calculate approved accommodation reimbursement from days and invoiced amount
def cal_approved_accommodation(days: int, invoiced_amount: float) -> float:
    limit = days * 400.0
    if invoiced_amount > limit:
        approved_accommodation = limit
    else:
        approved_accommodation = invoiced_amount
    return approved_accommodation


# Business function 1: Calculate Routine visits total reimbursement
def cal_visit_reimbursement(days: int, invoiced_amount: float) -> float:
    approved_accommodation = cal_approved_accommodation(days, invoiced_amount)
    return approved_accommodation + 200.0


# Business function 2: Calculate Off-site training total reimbursement
def cal_training_reimbursement(days: int, invoiced_amount: float) -> float:
    approved_accommodation = cal_approved_accommodation(days, invoiced_amount)
    return approved_accommodation + 300.0


# Business function 3: Calculate On-site project work total reimbursement
def cal_project_reimbursement(days: int, invoiced_amount: float) -> float:
    approved_accommodation = cal_approved_accommodation(days, invoiced_amount)
    return approved_accommodation + 500.0


# Calculate and output total reimbursable amounts for the three claims in Table 2
total_visit = cal_visit_reimbursement(2, 700.0)
print(f"Routine visits total reimbursement: {total_visit:.2f} CNY")

total_training = cal_training_reimbursement(3, 1200.0)
print(f"Off-site training total reimbursement: {total_training:.2f} CNY")

total_project = cal_project_reimbursement(4, 1800.0)
print(f"On-site project work total reimbursement: {total_project:.2f} CNY")

Reference Solution 2 for [Q2.2]

The helper system (cal_approved_accommodation) takes days and invoiced_amount and outputs approved_accommodation, which feeds into each of the three business systems (cal_visit_reimbursement, cal_training_reimbursement, and cal_project_reimbursement) to compute total_reimbursement:

System Structure Diagram (Solution 2): 1 Helper + 3 Business Functions


[Q3] Question 3

Problem Statement

A smart logistics park has several autonomous delivery vehicles, each with an integer ID. Vehicles with even-numbered IDs perform dedicated "Fresh-food delivery" tasks and receive a subsidy of CNY 50 each; vehicles with odd-numbered IDs perform "General merchandise delivery" tasks and receive a subsidy of CNY 30 each.

At the start of each morning shift, the park gets a list of IDs for vehicles assigned tasks that day. The system needs to print each vehicle's vehicle ID, task type, and operational subsidy. Single-vehicle processing must also be independently callable to handle vehicles added at short notice.

The vehicle ID list for the day is [5, 2, 7]. After printing information for all vehicles, print the total subsidy payable for the day, and then print the message "Morning dispatch complete" once.

  • [Q3.1] First provide a structured description of the steps, and then write the corresponding Python code.

Reference Solution for [Q3.1]

1. Structured Description of Steps

text
# Define a helper function to process a single vehicle ID and return its operational subsidy:
#     If the vehicle ID is even:
#         Set task type to "Fresh-food delivery" and operational subsidy to 50 CNY
#     Else:
#         Set task type to "General merchandise delivery" and operational subsidy to 30 CNY
#     Print the vehicle ID, task type, and operational subsidy
#     Return the operational subsidy
#
# Set the vehicle ID list for the day to [5, 2, 7],
# and initialize the total subsidy payable to 0 CNY
#
# For each vehicle ID in the vehicle ID list:
#     Call the helper function to print the vehicle's information and get its operational subsidy
#     Add the returned operational subsidy to the total subsidy payable
#
# Print the total subsidy payable for the day
# Print "Morning dispatch complete" once after all vehicles are processed

2. Python Code

python
# Helper function: Process a single vehicle, print its dispatch info, and return its subsidy
def process_vehicle(vehicle_id: int) -> int:
    if vehicle_id % 2 == 0:
        task_type = "Fresh-food delivery"
        subsidy = 50
    else:
        task_type = "General merchandise delivery"
        subsidy = 30
    print(f"Vehicle ID: {vehicle_id}, Task type: {task_type}, Subsidy: {subsidy} CNY")
    return subsidy


# Initialize vehicle ID list and total subsidy accumulator
vehicle_ids = [5, 2, 7]
total_subsidy = 0

# Loop through each vehicle ID in the list
for vehicle_id in vehicle_ids:
    # Call the helper function to print vehicle info and get its subsidy
    subsidy = process_vehicle(vehicle_id)

    # Accumulate total subsidy payable
    total_subsidy = total_subsidy + subsidy

# Output total subsidy payable and completion message once after the loop ends
print(f"Total subsidy payable: {total_subsidy} CNY")
print("Morning dispatch complete")