Lite / Building Machines That Respond / Week 3
int, float, str and list
A sensor file says "23.5". Add 0.4 and Python refuses. Why is a number in quotes not a number?
Why should I care?
Data from sensors, files and keyboards arrives as text. Calculations need numbers. Knowing the type of every value, and converting at the right moment, prevents a whole family of crashes and silent errors.
- Distinguish int, float, str, bool and list values and predict the type of an expression.
- Use //, % and / correctly, for example to split seconds into minutes and seconds.
- Convert text to numbers with int() and float() and explain when conversion fails.
Predict
What type is the result of 6 / 3 in Python 3?
- int (2)
- float (2.0)
- str ('2')
Guess first, then reveal
float: 6 / 3 is 2.0. The / operator always gives a float. Use // when you want a whole-number (floor) result.
Discover
Predict the value and type of each expression before you click it. Start with 7 / 2, 7 // 2 and 6 / 3, then the string ones. In 'Try your own numbers', find two numbers where // and / give the same value but different types.
What the interactive shows (text version)
The type inspector lists expressions with their Python results: 7 / 2 → 3.5 (float); 6 / 3 → 2.0 (float); 7 // 2 → 3 (int); 135 // 60 → 2 and 135 % 60 → 15 (int); "7" + "2" → '72' (str); "23.5" + 0.4 → TypeError; float("23.5") + 0.4 → 23.9; int("4.2") → ValueError; int(9.99) → 9. A second panel computes any two numbers with any operator and shows the result and its type.
Watch (optional)
Watch for: Watch the difference between / and //, and what % (modulo) gives. Notice the type each one produces.
A calm tour of Python's number types, its arithmetic operators and the difference between / and //.
“Python Tutorial for Beginners 3: Integers and Floats - Working with Numeric Data” by Corey Schafer (opens YouTube; streaming video uses a lot of data)
The video is optional. Everything you need is in this lesson's text.
Understand
Five types you will use every day
int: whole numbers, 135. float: numbers with a decimal point, 23.5. str: text in quotes, "23.5". bool: True or False, the result of a comparison. list: an ordered collection, [21.5, 22.0, 22.4]. Ask type(x) to check.
Three kinds of division
seconds = 135
minutes = seconds // 60 # 2 (floor division)
leftover_s = seconds % 60 # 15 (remainder)
print(f"{minutes} min {leftover_s} s")
print(7 / 2) # 3.5 (always a float)// and % together split a quantity into whole units and what is left over: seconds into minutes, parts into boxes.
Text is not a number until you convert it
"23.5" + 0.4 raises a TypeError. float("23.5") + 0.4 gives 23.9. int("42") gives 42, but int("4.2") raises a ValueError, and int(9.99) chops to 9, it does not round. With strings, + joins text: "7" + "2" is "72".
Explain it another way
Intuitive
A type is the kind of thing a value is. You can add two numbers or join two words, but adding a number to a word makes no sense, so Python stops and says so.
Technical
Python is dynamically but strongly typed: values carry their type, names do not. Operators dispatch on operand types; int and float mix (the result is float), but str and float do not mix under +.
Applied
Data loggers and serial sensors send readings as text, often with stray characters. Embedded and data code always has a conversion step that can fail, and the failure must be handled rather than ignored.
Worked example 1
A process takes 7384 s. Write it as hours, minutes and seconds with // and %.
hours = 7384 // 3600 = 2; rest = 7384 % 3600 = 184; minutes = 184 // 60 = 3; seconds = 184 % 60 = 4. So 2 h 3 min 4 s. Check: 2 × 3600 + 3 × 60 + 4 = 7384.
Common mix-ups
int(9.99) rounds to 10.
✓ int() chops the fraction: int(9.99) is 9. Use round() to round./ gives an int when the answer is whole.
✓ In Python 3, / always gives a float: 6 / 3 is 2.0.
Practice
Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.
Apply it
Write a program that takes a total run time in seconds (try 7384) and prints it as 'h min s'. Then add a line that reads a battery voltage stored as the text "3.71", converts it and prints whether it is below 3.5 V.
Reflect
Which type mistake do you think you are most likely to make, and how will you catch it?
Write your answer on paper or in your own notes. Lite never stores what you write.
Go further
- Python tutorial: numbers and text
The official tutorial's first look at numbers, strings and lists.