Lesson 4 of 30 · Getting Started
Data Types
Understand Python's four basic data types: strings, integers, floats and booleans. See why types matter and how to check them with type().
- 6 min read
- Beginner
- Reviewed
- The four basic types of data in Python
- How to find out the type of any value
- Why the type changes what an operation does
Every value has a type
Python treats text differently from numbers. You can multiply two numbers, but you cannot multiply two sentences. The kind of a value is called its data type.
Beginners need four types.
| Type | Python name | What it holds | Examples |
|---|---|---|---|
| String | str | Text | "hello", "42" |
| Integer | int | Whole numbers | 7, -3, 1000 |
| Float | float | Numbers with a decimal point | 3.14, -0.5, 2.0 |
| Boolean | bool | True or false | True, False |
Checking a type with type()
The type() function tells you the type of a value.
print(type("hello"))
print(type(42))
print(type(3.14))
print(type(True))It works on variables too. Python looks at the value inside.
name = "Ada" age = 36 height = 1.68 is_student = True print(name, type(name)) print(age, type(age)) print(height, type(height)) print(is_student, type(is_student))
You did not have to tell Python the type. It worked it out from the value. This is why Python is described as dynamically typed.
Strings: text
Single and double quotes both work, as long as they match.
print("Double quotes")
print('Single quotes')
print("It's easy to mix them")Integers and floats: numbers
Even 2.0 is a float, because of the point.
students = 30 average_score = 82.5 print(students, type(students)) print(average_score, type(average_score)) print(2.0, type(2.0))
Booleans: True or False
Note the capital first letter. Booleans answer yes-or-no questions, and you will use them all the time when your programs start making decisions.
is_raining = False has_umbrella = True print(is_raining) print(5 > 3)
Why types matter
The same symbol can do different things depending on the type. Predict the output before you run this.
print(5 + 5)
print("5" + "5")With numbers, + adds. With strings, + joins them end to end. "5" in quotation marks is text, not a number, even though it looks like one.
This program should calculate a total of 60, but it prints 202020. Find the type problem and fix it.
price = "20" quantity = 3 # The line below prints 202020 because price is a string. # Change ONE line above so the output is 60. print(price * quantity)
What is the data type of the value "100"?
Summary
- Every value has a data type.
stris text,intis a whole number,floatis a decimal number,boolisTrueorFalse.type()shows the type of a value or variable.- The type decides what an operator such as
+does.
In the next module you will put numbers to work with Python's maths operators.
Finished reading? Tick it off to track your progress.