graph LR
accTitle: Two stages of the grading software
accDescr: The stack of scanned sheets goes into the stage Process sheets, which writes a results file and a key file. The stage Build workbook reads the two files and produces the Excel workbook.
S[/"Stack of<br>scanned sheets"/] --> P[["Process sheets"]]
P --> R[("Results file")]
P --> K[("Key file")]
R --> B[["Build workbook"]]
K --> B
B --> W[("Excel workbook")]
Exercises - Programming foundations
Module 3: Python values, variables, expressions, and functions
Name:
Student number:
Choose one answer for each multiple-choice question. Answer the open questions with modular pseudocode or flowcharts.
M1) Variable update
In Listing 1, a Python 3.11 function updates the values of variables a, b, c, d, and e. The variables intended for arithmetic results are annotated as int, while the variables intended for logical results are annotated as bool. The final values are displayed using print.
a, b, c, d, and e and prints the final values (Question 1).
What is printed when the code in Listing 1 is executed?
a: 9 b: 1 c: 9 d: 9 e: Falsea: 10 b: True c: 9 d: 9 e: Truea: 1 b: True c: 9 d: 9 e: Truea: 10 b: 1 c: 9 d: 9 e: True
=: Assignment operator.==: Equality comparison operator, which produces a Boolean value.%: Modulo operator, which gives the remainder of a division.//: Floor-division operator; for the positive integers used here, it gives the integer quotient.not: Logical negation operator.or: Logical OR operator.
The keywords not and or perform Boolean logic here. They are different from the bitwise operators ~ and |.
M2) Concatenating words
In Figure 1, we have several versions of a Python function that concatenates two words passed as arguments and returns the concatenated result.
concatenate (Question 2).
Choose the correct version of the function concatenate that concatenates two words passed as arguments and returns the concatenated result:
+ in Python
The + operator concatenates strings in Python. For example, if word1 is "data" and word2 is "base", the expression word1 + word2 produces "database".
M3) Function returning None syntax
Which of the following will display only the message Hello, World!? The hello_world function should perform the display action and implicitly return None. Assume that the function main is the entry point for the program.
Choose the correct option:
M4) Does it run?
Consider the Python code snippets in Listing 3. Each snippet attempts to generate a random floating-point number between a lower bound (inclusive) and an upper bound (exclusive).
Which of the code snippets in Listing 3 will run without errors when executed?
Pay attention to the colon after each def header, the return statement, and whether every name used in test has been defined.
random: function from Python’srandommodule that returns a floating-point number in the interval \([0, 1)\).print: built-in function that displays a value.def: keyword used to define a function.return: statement that sends a value back to the function caller.
M5) Calling an algorithm
The algorithm AlgA in Listing 5 receives two numbers—labeled n1 and n2—and calls another algorithm, AlgB in Listing 4, to calculate a value based on the input.
AlgB receiving a number labeled n as input.
AlgA receiving two numbers labeled n1 and n2 as input and calling AlgB.
Given the inputs n1 = 2 and n2 = 3, what is the output of AlgA? Select the correct output from the following options:
- 5
- 6
- 13
- 23
M6) Folder-friendly format
Turkish names often contain special characters and diacritics that can cause issues when used for folder naming.
In Listing 6 (a), we provide a set of Python functions to clean, format, and adjust Turkish names for folder naming conventions by removing leading and trailing spaces, converting to lowercase, replacing punctuation and special characters, and adding underscores.
In Listing 6 (b), we demonstrate the usage of these functions to format a Turkish name for folder naming. Executing the test_format_folder_name function on the input "Çiğdem Yildiz! " (where the exclamation mark and trailing spaces are part of the input) transforms it into a clean, folder-friendly format, with each intermediate step printed in the terminal.
In Figure 2, various sequences show possible outputs of test_format_folder_name.
test_format_folder_name function for the input "Çiğdem Yildiz! ".
Which output sequence in Figure 2 corresponds to the correct result for test_format_folder_name shown in Listing 6 (b) after formatting the input "Çiğdem Yildiz! "?
In Python, a str is a sequence of characters. Key string methods and functions used include:
strip: Removes leading and trailing whitespace. Syntax:text.strip().replace: Substitutes a specific substring within a string. Syntax:text.replace(target, replacement).lower: Converts all cased characters in a string to lowercase. Syntax:text.lower().print: Outputs text to the terminal. Syntax:print(output_text).
test_format_folder_name function calls format_folder_name to format a Turkish name for use in folder naming. The format_folder_name function calls add_underscores, to_regular, to_lower, strip_punct, and trim_spaces in a nested expression. Python evaluates the innermost call first, so the intermediate results are printed to the terminal from trim_spaces through add_underscores (Question 6).
def trim_spaces(text: str) -> str:
"""Remove leading and trailing whitespace."""
result = text.strip()
print(f'"{result}"')
return result
def strip_punct(text: str) -> str:
"""Remove punctuation symbols."""
result = text.replace("!", "")
result = result.replace("?", "")
result = result.replace(".", "")
result = result.replace(",", "")
print(f'"{result}"')
return result
def to_lower(text: str) -> str:
"""Convert the text to lowercase."""
result = text.lower()
print(f'"{result}"')
return result
def to_regular(text: str) -> str:
"""Replace special characters."""
result = text.replace("ç", "c")
result = result.replace("Ç", "C")
result = result.replace("ğ", "g")
print(f'"{result}"')
return result
def add_underscores(text: str) -> str:
"""Replace spaces with underscores."""
result = text.replace(" ", "_")
print(f'"{result}"')
return resultdef format_folder_name(text: str) -> str:
"""Prepare a name for folder format."""
return add_underscores(
to_regular(
to_lower(
strip_punct(
trim_spaces(text)
)
)
)
)
def test_format_folder_name() -> None:
name_text = "Çiğdem Yildiz! "
print(f'"{name_text}"')
print(f'"{format_folder_name(name_text)}"')
if __name__ == "__main__":
test_format_folder_name()M7) Variable scope
In programming, variable scope defines the visibility and accessibility of variables within different parts of the code. In Listing 7, we have a Python code snippet with a function calculate and a main function. The function calculate takes two input parameters, a and b, and returns a floating-point value. The main function initializes variables a, b, and c, calls the calculate function, and prints the result.
We have three breakpoints (BREAKPOINT 1, BREAKPOINT 2, and BREAKPOINT 3) in the code to inspect the variable values at different stages of execution.
calculate and main. The code breaks at three different points (BREAKPOINT 1, BREAKPOINT 2, and BREAKPOINT 3) to inspect the variable values (Question 7).
def calculate(a: float, b: float) -> float:
c: float = 0.0
result: float = 0.0
# BREAKPOINT 2
if c < b + a:
c = a * 2
result = -1.0
# BREAKPOINT 3
result = a + b + c
return result
def main() -> None:
a: float = 2.0
b: float = 3.0
c: float = 4.0
c = calculate(b, a)
# BREAKPOINT 1
print(c)
if __name__ == "__main__":
main()Starting from the main function (i.e., you run the Python file), you are executing the code line by line and inspecting the variable values at each breakpoint. What are the values of a, b, and c in their respective scopes at the breakpoints (BREAKPOINT 1, BREAKPOINT 2, and BREAKPOINT 3) while executing the code?
Choose the correct option:
BREAKPOINT 1:a=2.0,b=3.0,c=-1.0/BREAKPOINT 2:a=2.0,b=3.0,c=4.0/BREAKPOINT 3:a=2.0,b=3.0,c=6.0.BREAKPOINT 1:a=2.0,b=3.0,c=11.0/BREAKPOINT 2:a=2.0,b=3.0,c=0.0/BREAKPOINT 3:a=2.0,b=3.0,c=11.0.BREAKPOINT 1:a=2.0,b=3.0,c=11.0/BREAKPOINT 2:a=3.0,b=2.0,c=0.0/BREAKPOINT 3:a=3.0,b=2.0,c=6.0.BREAKPOINT 1:a=2.0,b=3.0,c=-1.0/BREAKPOINT 2:a=3.0,b=2.0,c=0.0/BREAKPOINT 3:a=3.0,b=2.0,c=0.0.
M8) A local variable shadows a global one
What is the output of the code in Listing 8?
x and a function func.
Choose the correct option:
- The code will print
15and10. - The code will print
10and15. - The code will print
15and15. - The code will raise a
UnboundLocalError.
M9) Updating a global variable without global
What is the output of the code in Listing 9?
x and a function func.
Choose the correct option:
- The code will print
15and10. - The code will print
10and15. - The code will print
15and15. - The code will raise an
UnboundLocalError.
M10) Type hints
What is the output of the code in Listing 10?
add_one_to with type hints.
Choose the correct option:
- The code will print
6and raise aTypeError. - The code will print
6and4. - The code will raise a
TypeErrorand print4. - The code will print
6and4.5.
Grading scanned answer sheets (Background)
At the University of Twente, paper multiple-choice exams are graded automatically by ConTest. After the exam, the Examinations Office scans the stack of answer forms, and the software grades every student and delivers the results as an Excel workbook. Figure 3 shows the two stages of that software. The questions that follow design one stage each. The stages share only two files, so each question can be answered without the other.
The answer forms. ConTest offers two answer forms, which can be downloaded from the page above: form 38431 with up to 100 questions and options A to D, and form 25223 with up to 50 questions and options A to G. The positions of the bubbles differ between the two forms. The software reads three parts of a sheet:
- the form code, printed in the top-left corner;
- the student-number grid, with 7 columns, one per digit, and one bubble for each digit 1 through 9 and 0 in every column; and
- one question row per question.
Name, course, version, and exam date are handwritten and are not read, so all students are graded with the same key. The teacher block and the true/false block of form 25223 are not used.
The examiner fills in the correct answers on an ordinary answer sheet and marks the student number 0000000. Such a sheet is called the key sheet. Together with the stack, the examiner supplies N, the number of questions, and the names of the files to write.
The two files. Questions and student-number columns are numbered from 1, as printed on the form. An answer is a letter, Blank when no bubble was marked, or Multiple when several were.
- The results file has one row per student sheet in stack order: position in the stack, student number, the answer to every question, points, score (%), grade, blank rows, multiple rows, and reason. A sheet that is not graded is flagged: its row holds only the position and the reason.
- The key file has the correct letter for every question.
How to answer. Answer each question with modular pseudocode or flowcharts. Give every procedure inputs, outputs, and one responsibility, and let a main procedure call the others. Each question lists operations that already exist and that you may use without designing them. Naming the procedures, including those operations, is part of the task: a good name says what the procedure does.
Q1) Process the scanned answer sheets
Design the stage Process sheets. You may use the operations in Table 1.
| Operation | Needs | Gives |
|---|---|---|
| Scan a sheet | a sheet | an image of the sheet |
| Read the printed form code | an image | the form code, or Unreadable |
| Recognize the marked bubbles in one region | an image, a form code, a region | the collection of marked labels; for example {C}, {A, C}, or the empty collection {} |
| Detect how the image is oriented | an image | Upright, Upside down, or Unknown |
| Rotate an image | an image, an angle | the rotated image |
| Write rows to a file | a file name, a list of rows | nothing; one line per row |
A region is one group of bubbles: student-number column c or question row q. Recognizing marks needs the form code because the bubbles are in different places on the two forms. A bubble that the student filled and then crossed out, as the form’s adjustment instructions allow, is not reported.
Scoring. A question scores 1 point when the answer equals the key. Scores are always reported as percentages:
\[ \text{score} = 100\% \times \frac{\text{points}}{N}, \qquad \text{grade} = 1 + 9 \times \frac{\text{score}}{100\%}. \]
Compute the grade from the unrounded score, then round the score and the grade to one decimal place, with halves rounded up.
Levels. Table 2 splits the task into levels. Levels 1 to 4 build on each other. Levels 5 to 7 are independent extensions of level 4 and can be answered in any order. From level 2 onward, show only the procedures you add or change and label them with their level.
| Level | Situation | Your design must | Weight |
|---|---|---|---|
| 1. One sheet | One scanned student sheet on form 38431; every group of bubbles has exactly one mark. |
Read the student number and the N answers. |
15% |
| 2. Score one sheet | The key is given as a list of N letters. |
Score the answers and compute the score and the grade. | 15% |
| 3. A stack of sheets | A stack with one key sheet, which may be anywhere in the stack. | Find the key sheet, grade every other sheet, and write the results file and the key file. | 20% |
| 4. Which form is used | The exam may use either form. The form of the key sheet is the exam’s form. | Read the form code before reading any mark, and use it for every mark. Flag a sheet on a different form. | 10% |
| 5. Imperfect marks | A question row may be blank or have several marks. | Score such a row 0 points and count the blank and multiple-mark rows per student. | 5% |
| 6. Missing or inconsistent data | A student-number column is blank or has several marks, a student number was already graded, or the stack has no key sheet or more than one. | Flag a sheet with the reason instead of grading it; for a duplicate, grade the first sheet and flag the later one. Without exactly one key sheet, write no files and output the reason. | 15% |
| 7. Scanning problems | A sheet is upside down or in an unknown orientation, or its form code is unreadable. | Rotate an upside-down image before reading it; flag the other cases. | 5% |
Naming (5%) and test cases (10%). Name your procedures. Create test cases for your design: for every level you answered, give an input and the output you expect.
Work backwards from the results file. List every value you need about one sheet, and write one small procedure that obtains each value. A procedure that reads one group of bubbles can be reused for a digit and for an answer.
Q2) Build the results workbook
Design the stage Build workbook. The number of questions is the number of letters in the key file. You may use the operations in Table 3.
| Operation | Needs | Gives |
|---|---|---|
| Read a file | a file name | the list of rows in the file |
| Create a workbook | nothing | an empty workbook |
| Add a worksheet | a workbook, a name, column headings | the new worksheet |
| Append a row to a worksheet | a worksheet, the values | nothing |
| Save a workbook | a workbook, a file name | nothing; the file is saved |
Tasks. The tasks in Table 4 go from easy to complex.
| Task | Your design must | Weight |
|---|---|---|
| 1. Design the workbook | Name five worksheets: the grades, each student’s answers, the key, the flagged sheets, and a question analysis. For each, state what one row represents and list the column headings. Scores are percentages. | 25% |
| 2. Copy the files into worksheets | Read both files, separate the graded rows from the flagged rows, write the grades, answers, key, and flagged worksheets, and save the workbook. | 35% |
| 3. Analyze the questions | For every question, compute the percentage of graded students who answered it correctly, left it blank, or marked several options. The design must also work when no student was graded. | 25% |
Naming (5%) and test cases (10%). Name your procedures. Create test cases for your design: give a key file and a results file as input, and the worksheet rows you expect.
Write one procedure per worksheet. Most of them only copy fields: they add the worksheet with its headings and then add one row per item. Only the question analysis needs counting.