Variables and data types in Python — exercises with a receipt, temperatures, tips and your student profile (and a True that’s worth 1)

My first receipt in Python looked finished: it added correctly, calculated the VAT… and on the last line, the total, the program stopped with a TypeError: can only concatenate str (not "float") to str. I’d written print("Total: " + total + " €"), trying to glue a number to a text. It was the same mistake as in the theory, disguised in a place where I didn’t expect it. That’s what happens with the exercises in this topic: there are few concepts, but they show up where you least look for them.

Here you have four exercises (two basic, one intermediate and a challenge that brings the whole topic together with your student profile), three “What’s wrong here?” snippets to train your eye, the solutions commented line by line and a cheat sheet to keep at hand. If you need a refresher, go back to the theory or the practice. And if you don’t have Python yet, start with installing Python on Windows.

How to use this article

  1. Read the statement and the expected output. Your program has to give exactly that output with that data.
  2. Try to solve it in VS Code without looking at anything. Before writing, decide the type of each value.
  3. If you’ve been stuck for more than 10 minutes, read the hint, and only the hint.
  4. Compare with the commented solution. If yours is different but gives the same output, it counts too: read the “why it’s done this way” to see which decisions you made differently.

As in the practice, the starting data is written as text ("1.20"), which is what input() would give you. That way your output has to match the statement character by character. If you like, swap those texts for input() afterwards and try other values.

Exercise 1 (basic): The shopping receipt

Write a program that works out the receipt for three products: the subtotal, the VAT (21 %) and the total with VAT. The starting data is:

ProductPrice (as text)
Milk"1.20"
Bread"0.90"
Coffee"3.50"

The output has to be this:

--- Receipt ---
Milk: 1.2 €
Bread: 0.9 €
Coffee: 3.5 €
Subtotal: 5.6 €
VAT (21%): 1.18 €
Total: 6.78 €

Product names as str and prices as float. The VAT is the subtotal times 0.21. Round the VAT and the total to 2 decimals with round(), and use f-strings for each line of the receipt. Notice that 1.20 comes out as 1.2: that’s normal when printing a float.

Exercise 2 (basic): Temperature converter

Write a program that converts a temperature in degrees Celsius (which arrives as the text "100") to Fahrenheit and Kelvin, with these formulas:

  • Fahrenheit = Celsius × 9 / 5 + 32
  • Kelvin = Celsius + 273.15

The output has to be:

100.0 °C equals:
→ 212.0 °F
→ 373.15 K

One float variable for the degrees Celsius is enough (float("100") gives 100.0, that’s why the output says 100.0 °C). Work out each conversion in its own variable so the code reads well. The arrow → is a normal character: write it inside the text.

Exercise 3 (intermediate): Bill splitter

Write a program that splits a restaurant bill between several people, including the tip. The data arrives as text: bill amount "85.50", tip percentage "10" and number of people "4". The output:

--- Bill split ---
Subtotal: 85.5 €
Tip (10%): 8.55 €
Total with tip: 94.05 €
Each person pays: 23.51 €

float for the amount and the percentage, int for the people (there’s no such thing as half a person). The tip is bill * percentage / 100. Divide the total by the people at the end and round each amount to 2 decimals. The 10% in the tip line comes out without .0: think about which conversion achieves that.

Challenge exercise: Complete student profile

This exercise mixes the whole topic. With this starting data:

DataValue (as text or literal)
Name, degree, university"Sergio Medina", "GCID", "ULPGC"
Age"20"
Subjects and gradesFP1 "7.5" · Statistics "8" · Mathematics "6.5" · Databases "4"

generate this profile, with the average grade rounded to 2 decimals, the highest and lowest grade (with max() and min()), whether the student has passed (average ≥ 5) and the approximate credits (passed subjects × 6):

=============================
       STUDENT PROFILE
=============================
Name: Sergio Medina
Age: 20 years
Degree: GCID
University: ULPGC
-----------------------------
Subject 1 — FP1: 7.5
Subject 2 — Statistics: 8.0
Subject 3 — Mathematics: 6.5
Subject 4 — Databases: 4.0
-----------------------------
Average grade: 6.5
Highest grade: 8.0
Lowest grade: 4.0
Passed?: True
Estimated credits: 18
=============================

str for text, int for age and float for grades (float("8") gives 8.0, that’s why it appears like that in the profile). max(a, b, c, d) and min(...) work with separate variables. To count passed subjects without if, remember that a comparison gives True or False… and that True is worth 1. The lines of = and - are made by multiplying a text: "=" * 29.

What’s wrong here?

Three short snippets with one bug each. Before reading the explanation, predict what each one does: does it give an error? which one? or does it work but give something strange?

Snippet 1: the receipt total

total = 6.78
print("Total: " + total + " €")

Got it? This is the real output:

Traceback (most recent call last):
  File "receipt.py", line 2, in <module>
    print("Total: " + total + " €")
          ~~~~~~~~~~^~~~~~~
TypeError: can only concatenate str (not "float") to str

total is a float (6.78) and "Total: " is a str. For Python, + between a text and something else can only mean “glue”, and it only knows how to glue text to text. The ~~~~^~~~ in the traceback mark exactly the operation that fails: "Total: " + total.

Building messages with + mixing text and numbers. It’s my mistake from the opening story, and it shows up above all on the last line of a program, when you think you’ve already finished.

The fix, with both possible ways:

total = 6.78
print("Total: " + str(total) + " €")   # option 1: convert to text
print(f"Total: {total} €")             # option 2 (better): f-string
Total: 6.78 €
Total: 6.78 €

With f-strings you don’t have to convert anything: f"Total: {total} €" puts the number in the gap whatever its type. It’s shorter, more readable and doesn’t fail.

Snippet 2: the tip with decimals

tip_txt = "12.5"     # what input() returns if you type 12.5
tip_pct = int(tip_txt)
print(tip_pct)

Real output:

Traceback (most recent call last):
  File "tips.py", line 2, in <module>
    tip_pct = int(tip_txt)
ValueError: invalid literal for int() with base 10: '12.5'

The user has left a 12.5 % tip and the program blows up in the conversion. int() only accepts text that is a whole number: "12.5" has a point, so it gives ValueError: invalid literal for int() with base 10. It worked with "10", which is why the bug doesn’t show until someone types a decimal.

Choosing int() by looking at the example in the statement instead of thinking about which values the data can have. A percentage, a grade or a price can have decimals.

The fix:

tip_txt = "12.5"
tip_pct = float(tip_txt)   # float accepts "12.5" (and also "10")
print(tip_pct)
12.5

If what you want is an integer from a text with decimals, do two steps: int(float("12.5")) gives 12. But think about it first: here you’d lose half a point of tip.

Snippet 3: the sum that doesn’t give 3.30

milk = 1.10
bread = 2.20
subtotal = milk + bread
print("Subtotal:", subtotal)
print(subtotal == 3.30)

Real output:

Subtotal: 3.3000000000000003
False

This one doesn’t give an error, and that’s why it’s the sneakiest. 1.10 + 2.20 = 3.30 by hand, but in binary neither 1.10 nor 2.20 is stored exactly, and the sum comes out as 3.3000000000000003. That’s why the comparison with 3.30 gives False. It’s the same phenomenon as 0.1 + 0.2 in the theory.

Comparing the result of a calculation with decimals using ==. It can come out False even though it’s equal “by hand”.

The fix is to round to cents before showing or comparing:

milk = 1.10
bread = 2.20
subtotal = round(milk + bread, 2)   # round to cents before showing or comparing
print("Subtotal:", subtotal)
print(subtotal == 3.30)
Subtotal: 3.3
True

For money, round to 2 decimals as soon as you finish each calculation (round(x, 2)) and show it with :.2f. In the operators topic you’ll see more ways to compare decimals safely.

Commented solutions

Solution to exercise 1

The approach is the same in all four exercises: read, convert, calculate and show. Before writing, ask yourself about each value whether you’re going to do calculations with it. If not (the product name), it stays as a str. If so, it needs converting, and the next question is whether it can have decimals: money can, so float.

Adding the prices just as they arrive. "1.20" + "0.90" + "3.50" doesn’t give an error: it gives "1.200.903.50", because + between texts sticks them together. Python doesn’t know those texts are prices until you convert them with float().

# Solution to exercise 1 · The shopping receipt
# The prices arrive as text, as if you had read them with input()
p1_name = "Milk"
p1_price = float("1.20")        # float: money has decimals
p2_name = "Bread"
p2_price = float("0.90")
p3_name = "Coffee"
p3_price = float("3.50")

subtotal = p1_price + p2_price + p3_price
vat = round(subtotal * 0.21, 2)      # 21 % of the subtotal, rounded to cents
total = round(subtotal + vat, 2)

print("--- Receipt ---")
print(f"{p1_name}: {p1_price} €")
print(f"{p2_name}: {p2_price} €")
print(f"{p3_name}: {p3_price} €")
print(f"Subtotal: {round(subtotal, 2)} €")
print(f"VAT (21%): {vat} €")
print(f"Total: {total} €")

Why it’s done this way:

  • Each price is converted when it’s read (float("1.20")), not just before adding. That way, from that line on, the variable is already a number and there’s nothing else to remember.
  • Checking by hand: 1.20 + 0.90 + 3.50 = 5.60; 5.60 × 0.21 = 1.176, which rounded to cents is 1.18; 5.60 + 1.18 = 6.78. It matches the output.
  • round(subtotal, 2) in the print: the subtotal comes out as 5.6 and not 5.6000000000000005 because, with these particular prices, the sum comes out exact. Rounding it on display is a safeguard: with other prices it might not (as in snippet 3).
  • The VAT is rounded before adding it, as on a real receipt: the VAT you’re charged is already in cents. If you added the unrounded VAT (1.176), the total would be 6.776 → 6.78; here it’s the same, but not always.

Solution to exercise 2

The approach here is to copy the formula into Python as it is: the × is * and the fraction 9/5 is /. The only thing to check first is that Python does the operations in the same order as the formula.

# Solution to exercise 2 · Temperature converter
celsius_txt = "100"              # what would arrive from input()
celsius = float(celsius_txt)     # float: a temperature can be 36.6

fahrenheit = celsius * 9 / 5 + 32
kelvin = celsius + 273.15

print(f"{celsius} °C equals:")
print(f"→ {fahrenheit} °F")
print(f"→ {kelvin} K")

Why it’s done this way:

  • float and not int for the degrees, because a temperature can be 36.6. That’s why the output says 100.0 °C: it’s a float.
  • Checking by hand: 100 × 9 = 900; 900 / 5 = 180; 180 + 32 = 212. And 100 + 273.15 = 373.15.
  • celsius * 9 / 5 + 32 without brackets works because * and / come before +, and between themselves go left to right. The original statement wrote it as (Celsius × 9/5) + 32, and the brackets are fine too: they give the same result and sometimes read better.
  • One variable per conversion (fahrenheit, kelvin): the code reads like the formula and, if one comes out wrong, you know which to look at.
If you wanted to go the other way, from Fahrenheit to Celsius (subtract 32 and multiply by 5/9), could you write it without brackets?

No. The formula is (f - 32) * 5 / 9, and here the brackets really are compulsory. Without them, f - 32 * 5 / 9 first does 32 * 5 / 9 (17.77…) and then the subtraction: with 212.0 you’d get 194.22 degrees instead of 100.0.

In the Celsius to Fahrenheit conversion they weren’t needed because the multiplication already goes first and adding the 32 comes last, which is exactly what the formula asks for. When the addition or subtraction has to go first, you have to force it with brackets.

Solution to exercise 3

The approach starts with the order of the calculations: first the tip (it comes from the bill), then the total (bill plus tip) and finally the split (total divided by the people). Each step uses the result of the one before. The other decision is when to round: the tip and the total are amounts that actually get charged, so they’re rounded to cents as soon as they’re calculated, and the split is rounded only once, at the end.

# Solution to exercise 3 · Bill splitter
bill = float("85.50")        # euros: float
tip_pct = float("10")        # percentage: float, in case someone leaves 12.5 %
people = int("4")            # people: int, there's no such thing as half a person

tip = round(bill * tip_pct / 100, 2)
total = round(bill + tip, 2)
per_person = round(total / people, 2)   # round ONLY at the end

print("--- Bill split ---")
print(f"Subtotal: {bill} €")
print(f"Tip ({int(tip_pct)}%): {tip} €")
print(f"Total with tip: {total} €")
print(f"Each person pays: {per_person} €")

Why it’s done this way:

  • Three types for three values: float for money and percentage (someone might leave 12.5 %, as in snippet 2) and int for the people.
  • int(tip_pct) in the text: tip_pct is 10.0, and written as it is it would show Tip (10.0%). int() cuts the .0 to make it look tidy. Careful: with 12.5 % it would show 12%; for that case you’d need to show the float.
  • Trace of the calculations:
StepCalculationResult
tip85.50 × 10 / 100 = 8.558.55
total85.50 + 8.55 = 94.0594.05
per_person94.05 / 4 = 23.5125 → 2 decimals23.51
  • Rounding the last step loses 0.0025 € per person: between the four of them, one cent is missing to reach 94.05. In a real restaurant, someone would put in that cent; in the program, it’s a good question to think about.
What if each person paid their share of the bill and their share of the tip separately, rounding each one?

It looks the same, but it isn’t. The share of the bill is 85.50 / 4 = 21.375, which rounds to 21.38. The share of the tip is 8.55 / 4 = 2.1375, which rounds to 2.14. Added together: 23.52 €, one cent more than the 23.51 in the solution.

Between the four of them they’d pay 94.08 €, three cents too much. Each intermediate rounding can add or take away half a cent, and here both go up. That’s why it’s best to round as little as possible along the way.

Solution to the challenge exercise

The approach has three blocks, in this order: the data with its types, the calculations and, at the end, the profile. The prints at the end only read variables that are already calculated, so if a figure comes out wrong you know the bug is in the calculations block, not in the output.

The obvious way to count passes is four ifs: if a1_grade >= 5: passed_count = passed_count + 1, and the same for each grade. It works, but it’s eight lines. Adding up the comparisons does it in a single line, and it’s exactly what the topic wants you to see: a bool is also a number.

# Solution to the challenge exercise · Complete student profile
name = "Sergio Medina"
age = int("20")                   # age is a whole number
degree = "GCID"
university = "ULPGC"

a1_name = "FP1"
a1_grade = float("7.5")
a2_name = "Statistics"
a2_grade = float("8")             # float("8") gives 8.0
a3_name = "Mathematics"
a3_grade = float("6.5")
a4_name = "Databases"
a4_grade = float("4")

average = round((a1_grade + a2_grade + a3_grade + a4_grade) / 4, 2)
max_grade = max(a1_grade, a2_grade, a3_grade, a4_grade)
min_grade = min(a1_grade, a2_grade, a3_grade, a4_grade)
passed = average >= 5.0
# Each comparison gives True (1) or False (0): adding them counts the passes
passed_count = (a1_grade >= 5) + (a2_grade >= 5) + (a3_grade >= 5) + (a4_grade >= 5)
credits = passed_count * 6

print("=" * 29)
print("       STUDENT PROFILE")
print("=" * 29)
print(f"Name: {name}")
print(f"Age: {age} years")
print(f"Degree: {degree}")
print(f"University: {university}")
print("-" * 29)
print(f"Subject 1 — {a1_name}: {a1_grade}")
print(f"Subject 2 — {a2_name}: {a2_grade}")
print(f"Subject 3 — {a3_name}: {a3_grade}")
print(f"Subject 4 — {a4_name}: {a4_grade}")
print("-" * 29)
print(f"Average grade: {average}")
print(f"Highest grade: {max_grade}")
print(f"Lowest grade: {min_grade}")
print(f"Passed?: {passed}")
print(f"Estimated credits: {credits}")
print("=" * 29)

Why it’s done this way:

  • Each value with its type: text as str, age as int (it’s counted) and grades as float (even though "8" and "4" look like whole numbers, other grades won’t be).
  • The average is rounded on the same line where it’s calculated because it’s only used for display and comparison. Checking: 7.5 + 8 + 6.5 + 4 = 26; 26 / 4 = 6.5.
  • max() and min() take the four separate grades and return the highest (8.0) and the lowest (4.0). No need to compare by hand.
  • Counting passes without if is the trick of the exercise. Each comparison grade >= 5 gives a bool, and since True is worth 1 and False 0, adding them counts the passes. You can see it in the diagram and the trace:
Counting passed subjects by adding booleansThe grades 7.5, 8.0, 6.5 and 4.0 are compared with 5: they give True, True, True and False, which are worth 1, 1, 1 and 0. The sum gives 3 passed subjects and 3 times 6 gives 18 credits.FP17.5>= 5Trueis 1Statistics8.0>= 5Trueis 1Mathematics6.5>= 5Trueis 1Databases4.0>= 5Falseis 0passed_count = 1 + 1 + 1 + 0 = 3credits = 3 * 6 = 18
True is 1 and False is 0: adding the four comparisons counts the passed subjects without any if.
ComparisonResultWorth
a1_grade >= 5 (7.5)True1
a2_grade >= 5 (8.0)True1
a3_grade >= 5 (6.5)True1
a4_grade >= 5 (4.0)False0
sum3 → 3 × 6 = 18 credits
  • The brackets in (a1_grade >= 5) + … are compulsory. Without them, Python would do the additions first (5 + a2_grade…) and then compare, and the result would have nothing to do with it.
  • "=" * 29 repeats the text 29 times: it’s the same str * int operation that gave "555" in the theory, used for something useful.
What would “Estimated credits” show if you removed the brackets from the sum of comparisons?

It would show Estimated credits: 0. Without brackets the line becomes a1_grade >= 5 + a2_grade >= 5 + a3_grade >= 5 + a4_grade >= 5. The additions go first, and then Python chains the comparisons: a >= b >= c means “a >= b and b >= c”.

The first link already fails: 7.5 >= 5 + 8.0 compares 7.5 with 13.0, and gives False. The whole chain is False, which as a number is 0, and 0 × 6 = 0. There’s no error, just a zero that makes no sense.


Exam-style quiz

Now test yourself as in the exam. The FP1 quizzes look like this: 15 questions in 20 minutes (16 in 30 in the Sequences one), almost all single choice (each wrong answer subtracts a third of what the question is worth) and many «what does this code print?», with the odd fill in the gaps, matching or true or false. Here are 13 original questions on variables and data types. Answer without running anything, press Check and read the explanation for each one. These questions are also the question bank for the FP1 theory mock exam, which will mix them with those from the other topics.

Question 1Single choice

What is an algorithm?

  1. A finite sequence of precise steps that solves a problem
  2. A program written in Python
  3. A part of the processor
  4. An error that repeats inside a loop
Solution

Answer: A finite sequence of precise steps that solves a problem

An algorithm does not need a computer: «to work out 4 × 3, add 4 three times» is already an algorithm. Programming is translating algorithms into a language the computer understands.

Question 2Short answer

What does this program print? Write the exact output.

x = 5
y = x
x = 8
print(y)
Solution

Answer: 5

y = x copies into y the value x had at that moment (5). Changing x afterwards does not touch y: numbers are not «linked». The output is 5.

Question 3Single choice

What type does type(3 / 1) give?

  1. float
  2. int
  3. str
  4. bool
Solution

Answer: float

In Python 3, / is «true» division and always returns a float: 3 / 1 is 3.0. If you want an integer, use //.

Question 4Match

Match each value with its type:

42
4.2
'42'
False

Definitions:

  • str
  • int
  • bool
  • float
  • list
Solution
  • 42 → int
  • 4.2 → float
  • '42' → str
  • False → bool

With no decimals it is an int; with a decimal point, a float; between quotes it is text (str) even if it contains digits; and True/False are bool. list is left over: none of them is in square brackets.

Question 5Single choice

What happens when you run these lines?

age = input("Age: ")
print(age + 1)
  1. A TypeError, because input returns text
  2. It prints the age plus one
  3. It prints the age followed by a 1
  4. Python converts the age to a number by itself
Solution

Answer: A TypeError, because input returns text

input() always returns a str, even if you type 18. Adding a str and an int makes no sense to Python and raises TypeError. The fix is int(input(...)).

Question 6True or false

About variable names in Python:

  1. final_grade is a valid name.
  2. 2grade is a valid name.
  3. Grade and grade are two different variables.
  4. for can be used as a variable name.
Solution
  • T — final_grade is a valid name.
  • F — 2grade is a valid name.
  • T — Grade and grade are two different variables.
  • F — for can be used as a variable name.

A name can contain letters, digits and _, but cannot start with a digit. Python is case-sensitive. And reserved words (for, if, while, def…) cannot be used as names.

Question 7Short answer

What does this program print? Write the exact output.

a, b = 3, 10
a, b = b, a
print(a - b)
Solution

Answer: 7

a, b = b, a swaps the values in one line: now a is 10 and b is 3. So a - b is 10 − 3 = 7.

Question 8Single choice

What is int(7.9)?

  1. 7
  2. 8
  3. 7.9
  4. An error
Solution

Answer: 7

int() truncates: it keeps the whole part and throws away the decimals. round(7.9) would give 8. Careful with negatives: int(-7.9) is -7.

Question 9Fill in the gaps

Complete the program so that it reads a number with decimals and prints it times 2:

price = ____(____('Price: ')) and then print(price * 2).

Words:

  • str
  • input
  • int
  • print
  • float
Solution

price = float(input('Price: ')) and then print(price * 2).

input reads the text and float turns it into a number with decimals. With int it would fail if you type 2.5, and with str you would still have text.

Question 10Single choice

What is the difference between a compiled language and an interpreted one like Python?

  1. A compiled one is translated entirely into machine code before running; an interpreted one is translated while it runs
  2. An interpreted one does not need a computer
  3. A compiled one cannot have errors
  4. None: they are two names for the same thing
Solution

Answer: A compiled one is translated entirely into machine code before running; an interpreted one is translated while it runs

The CPU only understands machine code. A compiler translates the whole program at once and produces an executable; an interpreter (like python3) reads and runs one instruction after another. That is why in Python an error on line 20 does not show up until the program gets there.

Question 11Single choice

What does this program print?

name = "Ana"
print("Hello,", name, "!")
  1. Hello, Ana !
  2. Hello,Ana!
  3. Hello, name !
  4. An error, because it mixes text and variables
Solution

Answer: Hello, Ana !

print writes its arguments separated by a space (sep=' ' by default) and ends with a newline (end='\n'). That is why there is a space before the exclamation mark.

Question 12Short answer

What does this program print? Write the exact output.

x = 4
x = x * 2
x = x + 1
print(x)
Solution

Answer: 9

Each assignment uses the previous value: 4 → 4 × 2 = 8 → 8 + 1 = 9. x = x * 2 is not an equation: it means «work out x * 2 and store it in x».

Question 13Single choice

What is len('3.14')?

  1. 4
  2. 3
  3. 3.14
  4. An error, because it is a number
Solution

Answer: 4

The quotes decide: '3.14' is a str, and len counts its characters, point included. With the number 3.14 (no quotes), len would raise TypeError.

FP1 exam coming up?The 14 cheat sheets, the three solved practicals and a 14-day plan, in a free PDF.See the pack

Watch it step by step in Python Tutor

Open Python Tutor, choose Python 3 and paste this summary of the challenge. It’s the best place to see that a bool can be added:

a1_grade = 7.5
a2_grade = 8.0
a3_grade = 6.5
a4_grade = 4.0

passes1 = a1_grade >= 5      # True
passes4 = a4_grade >= 5      # False
passed_count = (a1_grade >= 5) + (a2_grade >= 5) + (a3_grade >= 5) + passes4
credits = passed_count * 6

total = "Credits: " + str(credits)
print(passes1, passes4, passed_count, total)

Its output:

True False 3 Credits: 18

What to look for, stepping with Next:

  1. After passes1 = a1_grade >= 5, the variable appears with the value True, without quotes: a comparison creates a bool.
  2. After passes4, it’s False, because 4.0 doesn’t reach 5.
  3. When passed_count is calculated, a 3 appears, an int. Three True (1 each) and one False (0) have been added: the result is no longer a bool.
  4. At credits, 3 × 6 = 18.
  5. At total, look at the str(credits): without it, "Credits: " + credits would give the TypeError from snippet 1. Try removing it and you’ll see Python Tutor mark the line in red.

Cheat sheet: variables and data types in Python

The essentials in 30 seconds: a variable is a name that points to an object, and the object carries the type. input() always returns text, so convert it when you read it. int for what’s counted, float for what’s measured, str for text and bool for yes or no. Floats are approximate: round for display.

Types and conversions

I want to…CodeResult
Find out the typetype(7.5)<class 'float'>
Text → integerint("19")19
Text → decimalfloat("7.5")7.5
Text with decimals → integerint(float("7.5"))7
Number → textstr(19)"19"
Drop decimals (cut)int(7.9)7
Roundround(7.9) / round(7.166, 2)8 / 7.17
Read a number from the keyboardfloat(input("Grade: "))a float
Accept a decimal commafloat("1,78".replace(",", "."))1.78

Text and numbers

I want to…CodeResult
Add numbers5 + 510
Glue text"5" + "5""55"
Repeat a text"=" * 5"====="
Mix text and a numberf"Total: {6.78} €""Total: 6.78 €"
Two decimals in a textf"{183.20000000000002:.2f}""183.20"
Count passes(7.5 >= 5) + (4.0 >= 5)1

Templates from the exercises

# Read, convert, calculate, show
price = float("3.50")                  # or float(input("Price: "))
vat = round(price * 0.21, 2)
print(f"VAT: {vat} €")

# Count with booleans
passed_count = (grade1 >= 5) + (grade2 >= 5) + (grade3 >= 5)

# Money with two decimals
print(f"Each instalment: {total / 3:.2f} €")

Symptom / likely cause

SymptomLikely cause
TypeError: can only concatenate str (not "int") to strYou’re gluing a number to a text with +: use an f-string or str()
TypeError: unsupported operand type(s)You’re calculating with a text you haven’t converted ("19" / 2)
ValueError: invalid literal for int()int() with a text that has decimals or letters: use float()
ValueError: could not convert string to floatDecimal with a comma, or a text that isn’t a number
NameError: name '…' is not definedMisspelt name, different capital letter or true instead of True
The result has digits glued together (55, 78.5)You’re adding text: a conversion is missing
You get 3.3000000000000003It’s an approximate float: round for display
An absurd result with no error (BMI 0.0)Units or brackets: do the maths by hand

Before handing in, ask yourself:

  1. Have I converted every value that comes from input() to the right type?
  2. Have I used float for everything that can have decimals?
  3. Do my messages mix text and numbers with f-strings rather than +?
  4. Have I checked by hand at least one result?

Got it? The next topic is Python operators: integer division, remainder, powers, comparisons and logic, which you’ll use in every program from now on.

Keep goingAll Python articles

Did this article help you? Here is how you can support SergioLearns →

Ready for the exam?FP1 theory mock exam — from Fundamentals to Text processing, against the clock and with your real mark (just like in the lab)