Back to homeDigital Culture · High School Year 1 · Change subject
Start for free
Prep 1 · Digital Culture
Programming and robotics · Text-based programming

Text-Based Programming with Python

Until now you've been dragging colored blocks. Now you'll write the same ideas as text: each line is an exact command and the computer carries it out as written, without guessing what you meant. Picture the program for your school cooperative that charges for tortas: how do you tell it, using only text, to subtract $\$45$ from a balance? You'll solve it by the end of the page.

Variables, data types, and I/O

Variable as a labeled box: three lines of code create the box puntos with a 0, add 1 to it, and display its value on the screen. Code 1 puntos = 0 2 puntos = puntos + 1 3 print(puntos) Variable (box) puntos 0 → 1 stores 0 reads, adds 1, stores puntos: 1 Screen

In Python, the = sign doesn't mean "is equal to": it means "store what's on the right in the box on the left." That's why puntos = puntos + 1 isn't a contradiction: first the right side is calculated with the value that was there, and then the result is stored.

Practice★☆☆Not started
Explain what a variable is using the analogy of a labelled 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 labelled 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★☆☆Not started
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 shop application: 13,…

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 shop application: 13, 3.75, "Ana", True.

Solve
Practice★☆☆Not started
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★★☆Not started
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★★☆Not started
Write a three-line program that asks for a person's name and age and writes 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 writes 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

Conditionals: `if`, `elif`, `else`

In daily life you make decisions like this all the time: if it rains, I take an umbrella; if not, sunglasses. In pseudocode it's written: si llueve → tomar paraguas → si no → tomar lentes de sol. Python does the same with a condition that compares values (<, >, <=, >=, ==, !=).

Python code with an if/else conditional: if edad is greater than or equal to 12 it displays "Puedes", and otherwise "Aún no". The lines of each block are indented. edad = int(input("Edad: ")) if edad >= 12: print("Puedes") else: print("Aún no") ← condition if true ← otherwise if false no indentation input

int(input("Edad: ")) asks for the data (it arrives as text) and converts it to an integer so it can be compared with $12$. The indentation tells Python which lines belong to the if and which to the else.

To decide among three cases (positive, negative, or zero) you use three branches: if n > 0, elif n < 0, and else (which can only be zero).

Practice★☆☆Not started
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★☆☆Not started
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★☆☆Not started
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★★☆Not started
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★★☆Not started
A program converts a numerical mark 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…

A program converts a numerical mark 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

Loops: `for` and `while`

Animation comparing a for loop and a while loop: a cursor moves through the lines of each code. In the for loop, each lap adds a mark and a bar whose height is proportional to 3·i, from i = 0 to 9. In the while loop, the cursor goes through the condition, the print, and the subtraction; a bar shrinks from n = 5 to 0 and a dot appears for each value displayed, until the condition stops being met. for: fixed number of times for i in range(10): print(3 * i) 10 laps, 10 lines on screen while: until... n = 5 while n > 0: print(n) n = n - 1

An example with for: the table of $3$ is written with for i in range(1, 11): and inside it print(3, "x", i, "=", 3 * i). The body repeats $10$ times. For the table of $7$ you just change the $3$ to a $7$; even better, store the number in a variable n and use n in the body.

Practice★☆☆Not started
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★★☆Not started
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★★☆Not started
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★★☆Not started
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★★★Not started
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

Functions

If your program greets in ten different places, without a function you copy the same lines ten times; with def saludar(): you write them once and call them with saludar(). If something needs fixing, you change it in just one place.

A function as a machine: the same function area_cuadrado receives the value 5 and returns 25, and receives 2.5 and returns 6.25; the squares with side 5 and side 2.5 are drawn on a unit grid to show their areas. call result def area_cuadrado(lado): return lado * lado area_cuadrado(5) area_cuadrado(2.5) 25 5 × 5 6.25 2.5 × 2.5

The parameter is the variable in the definition (lado); the returned value is what comes out with return. Careful: without a return, the function returns None ("nothing").

Practice★☆☆Not started
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★★☆Not started
Analyse 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…

Analyse 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★★★Not started
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

Syntax errors and logic errors

Two code windows: with a syntax error (unclosed quotation mark) the program doesn't start; with a logic error (nota1 + nota2 / 2) it starts but gives 7 instead of 5. Syntax error input("Tu nombre: ) doesn't start Logic error media = nota1 + nota2 / 2 nota1 = 4 nota2 = 6 result: 7 expected: 5 it runs, wrong result

To hunt down logic errors, do a trace: write down the value of each variable after each line and compare it with what you expected. That's how you discover, for example, an else: aprobados = 0 inside a loop that wipes out the count, or a stray if where an elif was needed.

Back to the beginning: to subtract a torta costing $\$45$ from a balance you write saldo = saldo - 45, and with an if saldo >= 45: you first check that there's enough. If the balance isn't enough, you report how much is missing and change nothing; if it is enough, you subtract and warn when little is left. A while repeats the charge as long as there are customers.

Practice★★★Not started
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★★★Not started
A shop applies the following policy: purchases under $\$30$ pay $\$4.50$ for shipping; purchases between $\$30$ and $\$50$ have free shipping; purchases over $\$50…

A shop 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★★★Not started
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★★★Not started
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★★★Not started
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 cancelled, 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

Looking for information when your program doesn't work

Almost any programming question has already been asked by someone else, and the answer is almost always one search away. But finding the right information requires knowing what to ask, where to look, and what to do with what you find.

Practice★★★Not started
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

Summary

See all the exercises in this section