Text-based programming
Until now you have been dragging colored blocks. Maybe you've built a score counter for a basketball game or a pizza-order app that way. Now you write the same ideas as text: each line is an exact instruction and the computer carries it out as written, without guessing what you meant. By the end you'll be able to trace and debug short programs like the ones on the AP® CSP exam. (On the exam you'll see AP pseudocode, where ← means =, and lists start at 1; Python lists start at 0.)
Variables, data types and input/output
Explain what a variable is using the analogy of a labeled box and describe what each line does: puntos = 0, puntos = puntos + 1, print(puntos). What value appears on…
Explain what a variable is using the analogy of a labeled box and describe what each line does: puntos = 0, puntos = puntos + 1, print(puntos). What value appears on screen, and why is it not an error to add something to a variable that "already had" a value?
Classify these values according to their data type (integer, float, string, or boolean) and give an example of how each type could be used in a store app: 13, 3.75,…
Classify these values according to their data type (integer, float, string, or boolean) and give an example of how each type could be used in a store app: 13, 3.75, "Emma", True.
Explain what the input() and print() commands do in Python, what the difference is between them, and write a two-line program that asks for your name and greets you…
Explain what the input() and print() commands do in Python, what the difference is between them, and write a two-line program that asks for your name and greets you using it.
Predict the output of this program without running it, following the value of the variables line by line: a = 4, b = 3, a = a + b, b = a - b, print(a), print(b). Write…
Predict the output of this program without running it, following the value of the variables line by line: a = 4, b = 3, a = a + b, b = a - b, print(a), print(b). Write the full trace (what each variable is worth after each line) and not just the result.
Write a three-line program that asks for a person's name and age and prints a complete sentence using them (for example, "Mei is 14 years old"). Explain what data type…
Write a three-line program that asks for a person's name and age and prints a complete sentence using them (for example, "Mei is 14 years old"). Explain what data type input() always returns and what int() is used for when asking for the age.
Conditionals: `if`, `elif`, `else`
The figure shows a flowchart and, next to it, the program that does the same thing, but with the condition covered. Write the missing condition on the if line (it must…
The figure shows a flowchart and, next to it, the program that does the same thing, but with the condition covered.
Write the missing condition on the if line (it must compare the edad variable with $12$), explain what int(input("Edad: ")) does, and why the lines inside the if and else are indented to the right.
Explain what a conditional is using an example from your daily life (if it rains I take an umbrella; if not, sunglasses) and write it in three lines of pseudocode:…
Explain what a conditional is using an example from your daily life (if it rains I take an umbrella; if not, sunglasses) and write it in three lines of pseudocode: condition, what happens if it is met, and what happens if it is not.
This program has three typical errors: nombre = input("Tu nombre: ), if nombre = "Fátima", print("Hola"). Find each error (an unclosed quotation mark, an = that should…
This program has three typical errors: nombre = input("Tu nombre: ), if nombre = "Fátima", print("Hola"). Find each error (an unclosed quotation mark, an = that should be == and explain the difference), rewrite the corrected program, and state what error message the computer would give in each case.
Write a program that asks for a number and says whether it is positive, negative, or zero. Indicate what structure you are using (a conditional with two or three…
Write a program that asks for a number and says whether it is positive, negative, or zero. Indicate what structure you are using (a conditional with two or three branches), what comparisons you make, and test it mentally with the values $7$, $-3$, and $0$.
A program converts a numerical score into a grade: less than $5$ is a "fail", from $5$ to $6.9$ is a "pass", and from $7$ onwards is "merit". Write it using if, elif,…
A program converts a numerical score into a grade: less than $5$ is a "fail", from $5$ to $6.9$ is a "pass", and from $7$ onwards is "merit". Write it using if, elif, and else, explain why the order of the conditions matters, and what would happen if the first condition were nota > 5.
Loops: `for` and `while`
Explain the difference between a for loop (repeat a known number of times) and a while loop (repeat while a condition is met), and give an everyday example of each:…
Explain the difference between a for loop (repeat a known number of times) and a while loop (repeat while a condition is met), and give an everyday example of each: running ten laps around the playground versus continuing to row until reaching the shore.
Write a for loop that displays the multiplication table for $3$ (from $3 \times 1$ to $3 \times 10$), indicate how many times the loop body repeats, and explain what you…
Write a for loop that displays the multiplication table for $3$ (from $3 \times 1$ to $3 \times 10$), indicate how many times the loop body repeats, and explain what you would change to display the table for $7$ without rewriting the whole program.
Read this program and explain what it does: n = 5, while n > 0:, print(n), n = n - 1, and at the end print("Done!"). Write the complete screen output and explain what…
Read this program and explain what it does: n = 5, while n > 0:, print(n), n = n - 1, and at the end print("Done!"). Write the complete screen output and explain what would happen if we forgot the line n = n - 1.
A classmate writes a program that asks for passwords until correct: clave = "", while clave != "sol":, and inside only print("incorrecta"). Explain why the program never…
A classmate writes a program that asks for passwords until correct: clave = "", while clave != "sol":, and inside only print("incorrecta"). Explain why the program never ends, what line is missing inside the loop (asking for the password again), and the general rule about while loops: something must be able to change the condition.
To select qualifiers for a robotics tournament, five scores (from $0$ to $10$) are read. A classmate has proposed this code to count how many are equal to or greater…
To select qualifiers for a robotics tournament, five scores (from $0$ to $10$) are read. A classmate has proposed this code to count how many are equal to or greater than $5.0$:
aprobados = 0
for i in range(5):
nota = float(input("Introduce nota: "))
if nota >= 5:
aprobados = aprobados + 1
else:
aprobados = 0
print("Total de aprobados:", aprobados)
- a) Predict what will be displayed on the screen if the user successively enters the scores: $6.0$, $8.0$, $4.0$, $9.0$, and $7.0$. Justify why the final result is not the expected one by locating the logic error in the conditional structure.
- b) Correct the code and modify it so that it discards invalid scores (less than $0$ or greater than $10$) from the count, displaying a specific warning message without adding to or resetting the counter.
Functions
Explain what a function is in a program and what advantage there is in writing def saludar(): once and being able to call it many times, instead of copying the same…
Explain what a function is in a program and what advantage there is in writing def saludar(): once and being able to call it many times, instead of copying the same lines over and over again.
Analyze this function: def area_cuadrado(lado): and inside return lado * lado. Explain what the parameter is, what the returned value is, and what each call would…
Analyze this function: def area_cuadrado(lado): and inside return lado * lado. Explain what the parameter is, what the returned value is, and what each call would display on the screen: print(area_cuadrado(5)), print(area_cuadrado(2.5)).
A team is developing software for a cash register using functions: a) When running this code, Python produces the error: TypeError: unsupported operand type(s) for -:…
A team is developing software for a cash register using functions:
def calculate_vat(price):
total = price * 1.21
pass # The programmer forgot to add the last line of this function
def apply_discount(total, discount):
result = total - discount
return result
base_price = 100.0
price_with_vat = calculate_vat(base_price)
final_price = apply_discount(price_with_vat, 10.0)
print("Final price:", final_price)
- a) When running this code, Python produces the error:
TypeError: unsupported operand type(s) for -: 'NoneType' and 'float'. Interpret the message and explain exactly how the valueNonetravels through the program's variables. - b) A classmate claims: "To fix it, you just need to change the line in the first function to
print(price * 1.21)". Refute their statement by explaining the functional difference between displaying a value on the screen and returning a value to the main call. - c) Correct the code and add a function
is_valid(price)that returns a boolean value (TrueorFalse) to verify that the base amount is not negative before processing it.
Syntax errors and logic errors
In the game "guess a secret number from $1$ to $100$", your classmate claims: "With a loop of fixed attempts it is impossible to guarantee that the user guesses…
In the game "guess a secret number from $1$ to $100$", your classmate claims: "With a loop of fixed attempts it is impossible to guarantee that the user guesses correctly; we are always forced to use an infinite while until they guess it".
- a) Refute their claim: justify mathematically why $7$ attempts are sufficient to guess any number between $1$ and $100$ with absolute certainty if a binary search strategy is used (always asking for the midpoint).
- b) Design the game in Python or pseudocode with a limit of $7$ lives. The program must stop both if the user guesses correctly before running out of attempts and if they run out of lives, displaying different final messages. Justify the logical stop condition you have chosen.
A store applies the following policy: purchases under $\$30$ pay $4{,}\$50$ for shipping; purchases between $\$30$ and $\$50$ have free shipping; purchases over $\$50…
A store applies the following policy: purchases under $\$30$ pay $4{,}\$50$ for shipping; purchases between $\$30$ and $\$50$ have free shipping; purchases over $\$50$ have free shipping and a $10\ \%$ discount on the purchase price.
A student programmed this code:
precio = float(input("Total compra: "))
if precio > 50:
total = precio * 0.90
if precio >= 30:
total = precio
else:
total = precio + 4.50
print("Total a pagar:", total)
- a) Trace the execution with a purchase of $60{,}\$00$. What final price does the program print? Justify why this logic error occurs when chaining the conditionals.
- b) Rewrite the program correctly using a nested conditional structure or with
elif, and include a validation that warns if a negative price or zero is entered.
Observe the following program, whose objective is to ask the user for their age and determine if they are of legal age to vote (from $18$ years old completed): a) If you…
Observe the following program, whose objective is to ask the user for their age and determine if they are of legal age to vote (from $18$ years old completed):
if edad >= "18":
print("Puedes votar")
edad = input("Dime tu edad: ")
else:
print("No puedes votar")
- a) If you try to run the program as it is, on which line will the Python interpreter stop and why will it not reach the
inputline? - b) Identify and classify all the errors present, distinguishing between syntax errors (which prevent compiling/interpreting) and type or logic errors during execution.
- c) Rewrite the corrected code and introduce a check to prevent the program from crashing if the user enters their age as text (for example, typing "eighteen").
To regulate a school crossing, this algorithm in pseudocode is proposed for a traffic light with a pedestrian push-button: a) Detect a serious road safety flaw in the…
To regulate a school crossing, this algorithm in pseudocode is proposed for a traffic light with a pedestrian push-button:
while true:
cars_green = ON, pedestrians_red = ON
if button_pressed == 1:
wait(5)
cars_green = OFF, cars_amber = ON
wait(3)
cars_amber = OFF, cars_red = ON
pedestrians_red = OFF, pedestrians_green = ON
wait(10)
pedestrians_green = OFF, pedestrians_red = ON
- a) Detect a serious road safety flaw in the transition back: when the pedestrian green light turns off, what happens immediately to vehicular traffic in the next iteration of the loop?
- b) Design an improvement to the algorithm (in pseudocode or structured text) that resolves this flaw and also prevents traffic congestion: if pedestrians repeatedly press the button, the traffic light must always guarantee a minimum of $20$ uninterrupted seconds of green for cars between cycles.
Design the algorithm for a school cafeteria top-up and payment terminal meeting the following technical requirements: The card starts with an initial balance of…
Design the algorithm for a school cafeteria top-up and payment terminal meeting the following technical requirements:
-
The card starts with an initial balance of $20{,}\$00$ and each meal costs $4{,}\$50$.
-
In a loop, the program asks how many meals the user wants to consume today.
-
If the available balance is insufficient to pay for the requested amount, the transaction is canceled, the missing amount is displayed, and the balance remains unchanged.
-
If there is sufficient balance, the amount is deducted and it is checked whether the remaining balance is less than $5{,}\$00$, displaying in that case the warning «Low balance: top up soon».
-
The program must terminate automatically when the remaining balance is less than the price of a single meal ($4{,}\$50$).
-
Justify which type of loop you have used and explain how you prevent a user from entering a negative number of meals to artificially increase their balance.
A grading system calculates the final grade by applying the following weights: Classwork ($20\ \%$), Workshop practical ($30\ \%$) and Theory exam ($50\ \%$). The…
A grading system calculates the final grade by applying the following weights: Classwork ($20\ \%$), Workshop practical ($30\ \%$) and Theory exam ($50\ \%$). The teacher has programmed the formula as follows:
classwork = float(input("Classwork grade: "))
workshop = float(input("Workshop grade: "))
exam = float(input("Exam grade: "))
final_grade = classwork * 0.20 + workshop * 0.30 + exam * 0.50 / 3
if final_grade > 5:
print("Pass")
else:
print("Fail")
- a) Predict the result displayed by the program if the student obtains a $10.0$ in all three sections. Interpret operator precedence to justify the incorrect numerical value stored in
final_grade. - b) Justify why this error is a logic error and not a syntax error, and argue why logic errors pose a much greater risk in engineering or control programs than syntax errors.
- c) Detect a second logic error in the condition of the
ifstatement regarding the usual official grading criterion (passing with $5.0$) and write the final version of the corrected program.