Python · Lesson 1.5
Types and converting
Check what kind of value you have, and turn text into numbers (and back).
1Every value has a type
type() tells you what kind of value something is. The four basic types are int, float, str (text) and bool (True or False).
print(type(42))
print(type(3.14))
print(type("42"))
print(type(True))Practice
Print the type of each value below, one per line.
a = 7 b = "7" c = 7.0 # Print type(a), type(b), type(c)
2Text that looks like a number
Data often arrives as text, and "10" + "5" joins text instead of adding. Convert with int() or float() before doing maths.
a = "10" b = "5" print(a + b) print(int(a) + int(b))
Practice
The two values came from a file as text. Convert them and print their sum: 27.5.
units = "20" extra = "7.5" # Convert and print the sum
3Cleaning text before converting
int() fails on text like "1,200" or " 42 " with spaces. Remove the extra characters first with .replace() and .strip().
raw = " 1,200 "
clean = raw.strip().replace(",", "")
print(int(clean) * 2)Practice
Turn "$3,450" into the number 3450, then print it times 2.
raw = "$3,450" # Clean, convert, print times 2
4Numbers back to text, and to whole numbers
str() turns a number into text, and int() on a float cuts off the decimals rather than rounding.
score = 87
print("Score: " + str(score))
print(int(9.99), round(9.99))Practice
Print int(price) and then round(price) on separate lines, to see the difference.
price = 4.7 # Two prints
Quick check
What does print("3" * 2) show?