Quiz
Warm-up from lesson 1-1: you sorted values into types. What is the type of `"3.5"`, quotes included?
Converting between types
Every value that enters a program from the outside, typed input, a file, a web request, arrives as text. Until you convert it, you cannot do math with it. Conversion functions are the doorway between the outside world and arithmetic, which is why this small lesson unlocks everything interactive that follows.
Python never guesses a conversion for you. "3" + 3 is an error on purpose. When you have a value of the wrong type, convert it explicitly:
| Function | Converts to | Example |
|---|---|---|
int(x) | whole number | int("42") → 42 |
float(x) | decimal | float("3.5") → 3.5 |
str(x) | text | str(42) → "42" |
Two behaviors to know precisely:
int(9.9)gives9. Converting a float to int chops off the decimal part, it does not round.round(x)rounds to the nearest whole number, andround(x, 2)rounds to 2 decimal places.
If the text cannot be converted, like int("hello"), the program stops with a ValueError. Unit 9 shows how to survive that.
Code exercise · python
Run this and check each conversion against the table. Look closely at the difference between `int(9.9)` and `round(9.9)`.
Quiz
What does `int(7.8)` evaluate to?
Code exercise · python
Your turn. The variable `raw` holds a price as text. Convert it to a float, apply a 10% discount (multiply by 0.9), and print the result rounded to 2 decimal places using `round()`.
Problem
Without running it: what does `float("7") + 1` evaluate to, written exactly as Python would print it?