Back to homeAP® Computer Science Principles · AP Computer Science Principles · Change subject
Start for free
Notes

Exercises: Text-based programming

Practice★☆☆
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?

Solve
Practice★☆☆
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.

Solve
Practice★☆☆
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.

Solve
Practice★☆☆
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.

start ask for age is age ≥ 12? yes you can participate no not long to go edad = int(input("Edad: ")) if ?: print("Puedes") else: print("Aún no")

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.

Solve
Practice★☆☆
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.

Solve
Practice★☆☆
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.

Solve
Practice★☆☆
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.

Solve
Practice★☆☆
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.

Solve
Practice★★☆
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.

Solve
Practice★★☆
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.

Solve
Practice★★☆
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$.

Solve
Practice★★☆
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.

Solve
Practice★★☆
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.

Solve
Practice★★☆
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.

Solve
Practice★★☆
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)).

Solve
Practice★★☆
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.

Solve
Practice★★★
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)
  1. 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.
  2. 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.
Solve
Practice★★★
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".

  1. 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).
  2. 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.
Solve
Practice★★★
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)
  1. 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.
  2. 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.
Solve
Practice★★★
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")
  1. 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 input line?
  2. b) Identify and classify all the errors present, distinguishing between syntax errors (which prevent compiling/interpreting) and type or logic errors during execution.
  3. 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").
Solve
Practice★★★
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
  1. 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?
  2. 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.
Solve
Practice★★★
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)
  1. 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 value None travels through the program's variables.
  2. 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.
  3. c) Correct the code and add a function is_valid(price) that returns a boolean value (True or False) to verify that the base amount is not negative before processing it.
Solve
Practice★★★
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.

Solve
Practice★★★
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")
  1. 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.
  2. 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.
  3. c) Detect a second logic error in the condition of the if statement regarding the usual official grading criterion (passing with $5.0$) and write the final version of the corrected program.
Solve
Practice★★★
Unit challenge. As a beginner data analyst, your mission is to create a Python program to analyze the thermal impact on your surroundings and propose energy-efficient…

Unit challenge. As a beginner data analyst, your mission is to create a Python program to analyze the thermal impact on your surroundings and propose energy-efficient habits.

  1. Data collection: Visit the official National Weather Service (weather.gov) website and record the maximum temperature recorded in your city over the last $5$ consecutive days.

  2. Text-based programming: In a free online editor such as Trinket.io, write a Python script that stores these $5$ values in a list. Using a for loop and if-else conditionals, program the automatic calculation of the average temperature ($\bar{x}$) and the identification of the hottest day.

  3. Report and proposal: Produce a brief document that includes the commented source code, a screenshot of the console output, and a justified proposal with two home climate control measures if the average exceeds $21.5$ °C.

Assessment criteria:

  • Syntactic correctness of the text code (handling of lists, loops, and conditional structures).

  • Accuracy in importing real data from the National Weather Service and precision of the mathematical calculation.

  • Clarity of comments in the program and technical feasibility of the energy proposal.

Solve