Data types
Python · Unit 1: First steps
- Free
- Python
- 11 exercises
Every value has a type: int for whole numbers, float for decimals, str for text and bool for true or false.
type() tells you what type something is.
print(type(42))
print(type(3.5))
print(type("hello"))
print(type(True))Prints
<class 'int'> <class 'float'> <class 'str'> <class 'bool'>
A number inside quotes is text: "42" is str, not int.
And between texts, + doesn't add: it glues them.
print(type("42"))
print("Hello" + "world")Prints
<class 'str'> Helloworld
To change type use int(), float() or str().
int("5") turns the text into the number 5, and str(5) does the opposite.
print(int("5") + 5)
print(str(5) + "5")
print(float("2.5"))Prints
10 55 2.5
Text plus a number is an error (TypeError): Python doesn't know if you want to add or to glue.
Convert the number with str(), or use commas in print().
price = 50
print("Costs " + str(price))
print("Costs", price)Prints
Costs 50 Costs 50
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Multiple choice
What type is
True?2. Complete the code
Fill in to find out what type
3.0is.print(___(3.0))3. Predict the output
What does this code print?
print(type(7 / 2))4. Put the lines in order
Order the lines to print the type of a price.
5. Multiple choice
Which of these values is text (
str)?6. Predict the output
What does this code print?
print("3" + "4")7. Complete the code
Fill in to turn the text into a number and add 1 to it.
age = ___("17") print(age + 1)8. Find the bug
This program should print double 20. Which line has the error?
text = "20" double = text * 2 print(double)9. Multiple choice
What happens with
"5" + 5?10. Find the bug
This program should print "Emma is 17 years old". Which line has the error?
age = 17 phrase = "Emma is " + age print(phrase, "years old")11. Predict the output
What does this code print?
a = "7" b = 3 print(int(a) + b) print(a + str(b))
It opens in your browser. It is free and you do not need an account to start.