Python 1.4Free video10 minLesson 4 of 6 in Module 1
Data Types
Know the basic types and how they convert.
Free sample. Everything in this module opens with a free account.
Watch or read the lesson: Data Types
01Built-in data types
Imagine you are reading a settings file, and you come across this line:
notifications = "False"
It looks straightforward: notifications are turned off. But notice something. That False is inside quotes, which means Python treats it as a string, not a Boolean. That distinction matters when you convert values from one type to another. You will test this setting later in the lesson, once you have looked at the basic types and the functions that convert between them.
Every object has a type
In the previous lesson you saw that everything in Python is an object, and every object has a type. But why does the type matter?
Because the type determines what you can do with a value. You can add two numbers together. You can join two pieces of text. But what happens if you try to add a number to a string? That depends on the types involved, and that is why understanding data types is so important.
Python has a built-in function called type() that tells you the type of any object. You will use it to explore the basic types one at a time.
int and float
First come integers: whole numbers, like 3, 10 or 100. In Python this type is called int. Ask Python for the type of 3:
type(3)
int
Python tells you it is an integer. (That is how a notebook such as Colab displays a type. If you print it, or run Python outside a notebook, you see the longer form <class 'int'>. Both say the same thing.)
What about a number with a decimal point, like 24.75? That is a floatKey termA number with a decimal point: 24.75, 2.0., short for floating-point number, and checking its type confirms it:
type(24.75)
float
complex
There is one more numeric type you might come across, especially in engineering or signal processing: complex numbers. For example, 1 + 2j. Here the j marks the imaginary part of the number.
type(1 + 2j)
complex
You probably will not use complex numbers very often, but it is good to know that Python supports them.
isinstance
So far you have used type() to check an object's type. There is another useful function, isinstance(), which checks whether an object is an instance of a particular type. It answers with True or False. Is 1 + 2j a complex number?
isinstance(1 + 2j, complex)
True
That is useful when you want to check the type of a value before working with it.
bool
Next come Booleans, or bool for short. A Boolean has only two possible values: True or False. That is it.
You will see Booleans everywhere in Python, because so many questions have a yes-or-no answer. Has an order been delivered? True or False.
One important thing to remember: Python writes these values with capital letters, and without quotes. True and False, not true, and not "True". Check the type of True and you get bool:
type(True)
bool
str
Now, what about text? For that, Python has strings. The type is called str, short for string. A string is a sequence of characters. It could be a name, a sentence, an email address, or even a number written as text: "100" is a string, because it is in quotes.
type("Green Bowl")
str
You can create strings with either single quotes or double quotes; 'Asha' and "Asha" are the same string, and Python treats both the same way. If you need a string that spans multiple lines, put three quotes at the beginning and three at the end.
None
There is one more basic type, and this one is a little different. It is called NoneType, and it has just one value: None. You use None to represent the absence of a meaningful value.
Say you are storing customer ratings, and a customer has not rated their order yet. So you write:
rating = None
type(rating)
NoneType
Why not just use zero? Because zero could be an actual rating. None says something different: there is no rating yet. That distinction becomes really useful when you work with real data, where missing values are common.
Single values, and collections
That is your first look at Python's basic types: int, float, complex, bool, str and NoneType. Each of them represents a single value.
Python also has collection types, like lists, tuples, sets and dictionaries, which let you work with groups of values. You will explore those properly in the data structures module.
02Dynamic typing and type annotations
The type belongs to the object, not to the name. So a name can be rebound to an object of a different type. Suppose you write:
items = 3
type(items)
int
Right now, items refers to an integer. What happens if you change it to 3.5? Does Python allow it?
items = 3.5
type(items)
float
It works perfectly well. Now items refers to a float. This is the same rebinding you saw in the previous lesson, now with an object of a different type. And this is what it means to say that Python is dynamically typed: a name has no fixed type of its own, so it can refer to an object of any type.
Type annotations
If you have looked at modern Python code, you may have seen a type written right next to a variable name, something like this:
items: int = 3
items, type(items)
(3, int)
The : int part is called a type annotationKey termThe intended type, written after a colon: items: int = 3. Python does not check it; editors and type checkers do.. It is a way of saying that items is intended to refer to an integer.
What if you ignore the annotation?
Here is a question. What if you keep the annotation int, but assign a string, writing items: int = "3"? You are saying items should be an integer, but you are giving it a string. Will Python raise an error? Think it through before reading on.
I have a guess. Show meHide the answer
items: int = "3"
items, type(items)
('3', str)
Nothing happens. The code runs just fine, and items is the string '3'.
That is because Python does not enforce type annotations when the program runs. They are mainly there to help you write and maintain better code. Editors, and tools called type checkers, can read the annotations and point out likely mistakes, like this one. But the annotation itself does not stop you from assigning a different type.
Values do not always arrive in the type you need
Now that you understand the types themselves, it is time for something you will use all the time: type conversion, turning a value of one type into a value of another.
When you start working with real data, you quickly discover that values do not always arrive in the type you need. Imagine someone enters their age in a form. They type 25. That looks like a number, but when that input comes into Python as text, it is actually the string "25". If you want to do calculations with it, you need to convert it into a number first.
03Type conversion
Python makes this fairly easy. For most basic types, there is a built-in function with the same name as the type, and you use it for conversion. float(5) converts the integer 5 into 5.0, a float:
float(5)
5.0
And str(20) converts the integer 20 into the string "20":
str(20)
'20'
The quotes in the output tell you the result is a string. One thing to keep in mind: converting a value does not modify the original object. Instead, you get an object of the requested type back.
Converting a float to an int
Now something slightly more interesting. What do you think int(1000.5) gives? Will Python round it up to 1001, or will it give 1000? Think it through before reading on.
I have a guess. Show meHide the answer
int(1000.5)
1000
You get 1000.
int truncates toward zero
This is important. When you convert a float into an integer with int(), Python does not round it. It truncates the number toward zero: in other words, it removes the fractional part. So 1000.5 becomes 1000.
And with a negative number:
int(-7.9)
-7
You get -7, not -8. Removing the fractional part moves the number toward zero, and for a negative number, toward zero is upward. Rounding down would have given -8.
Converting a string to an int
int() can also convert strings into numbers. int("10") gives the integer 10:
int("10")
10
But there is a catch: the string has to represent a valid integer. What if you try "10p"?
int("10p")
ValueError: invalid literal for int() with base 10: '10p'
Python raises a ValueError. The message says that '10p' is an invalid literal for int with base 10, which makes sense. The letter p is not part of a valid integer, so Python cannot convert that string into an integer. (Base 10 means ordinary decimal digits, 0 to 9.)
Joining text and a number
Now something practical. Say you are writing a small program to congratulate someone on their coding progress. You have a name, Asha, and the number of lines she has written, which is 100:
name = "Asha"
lines = 100
You want to print the message "Congratulations, Asha! You have written 100 lines of code."
The + operator can join strings together. That is called concatenation. So you try building the message with +, including the lines variable.
Before you run it, think about the types involved. The pieces of the message are strings, and lines is an integer. What do you think happens when you join them? Think it through before reading on.
I have a guess. Show meHide the answer
print("Congratulations, " + name
+ "! You have written " + lines + " lines of code.")
TypeError: can only concatenate str (not "int") to str
You get a TypeError. Python tells you it can only concatenate a string with another string, not with an integer.
But why? Think about what the + operator does. Between two numbers, it adds them. Between two strings, it joins them. Here you are mixing a string and an integer, and Python does not define + between those two types.
Convert before you join
So how do you fix it? Convert lines into a string first, by wrapping it in str():
print("Congratulations, " + name
+ "! You have written " + str(lines) + " lines of code.")
Congratulations, Asha! You have written 100 lines of code.
Now it works. This is a good example of why type conversion matters. Sometimes the value you have is perfectly valid, but it is not the right type for the operation you are trying to perform.
Back to the settings file
Now return to the settings file from the start of the lesson, and convert the string "False" with bool():
notifications = "False"
What do you expect bool(notifications) to give: True or False? Think it through before reading on.
I have a guess. Show meHide the answer
bool(notifications)
True
Python returns True. But why? The text literally says False.
How bool reads a string
When you convert a string into a Boolean, Python does not read the text and try to work out whether it says True or False. Instead, it checks whether the string is empty. An empty string converts to False:
bool("")
False
And any non-empty string converts to True:
bool("Hello")
True
That explains bool("False"). The string contains five characters:
len("False")
5
so it is not empty, and it converts to True. In fact, even a string containing just one space converts to True:
bool(" ") # one space
True
This is something to watch out for when you work with configuration files or user input. If a settings file contains the text "True" or "False", do not assume you can convert it directly with bool().
Compare the text instead
Instead, compare the text with "True":
text_value = "False"
text_value == "True"
False
The comparison checks what the text actually says, so the setting "False" gives False, which is what you meant.
04Recap and challenge
Every value in Python is an object with a type, and type() tells you what it is: int, float, complex, bool, str or NoneType. The type belongs to the object, so a name can be rebound to a value of a different type, and type annotations do not change that, because Python does not check them when the program runs.
Conversion functions like int(), float(), str() and bool() give you a new object of the type you ask for. int() truncates a float toward zero, raises a ValueError for text that is not a valid integer, and bool() of a string only checks whether the string is empty.
So before using a value, check whether its type supports the operation you need. And when you convert it, predict both the new value and its type.
Your challenge
Try these four conversions yourself:
int(-7.9)
float("1e3")
bool(" ")
str(None)
- What does
int(-7.9)return? - What happens when you convert the string
"1e3"into a float? - What does
boolof a single space return? - What do you get from
str(None)?
For each one, predict both the value and its type. Then run the code and see whether you got it right.
Next, you will learn how to take input from users and display output in a clean, readable format.
Key terms: Data Types
The words this lesson introduces, each in one line. The module’s glossary collects them all, and the AI glossary has every term across the courses.
- bool
- True or False. The type of
TrueandFalse, both keywords, written with a capital letter. - complex
- A number with real and imaginary parts, such as
1 + 2j. Thejmarks the imaginary part;type(1 + 2j)is<class 'complex'>. - dynamic typing
- A name can refer to an object of any type, and can be rebound to an object of a different type:
items = 3, thenitems = 3.5. - float
- A number with a decimal point:
24.75,2.0. - int
- A whole number:
3,-7,1000. - None
- No value. The only value of the type
NoneType:rating = Nonefor an order not rated yet, which is different from a rating of0. - NoneType
- The type whose only value is
None.type(None)gives<class 'NoneType'>. - str
- Text, a sequence of characters, written in single, double or triple quotes.
- type
- Determines what values an object can hold, and what you can do with it.
type(x)shows it. - type annotation
- The intended type, written after a colon:
items: int = 3. Python does not check it; editors and type checkers do.
Quiz: Data Types
Your first pick on each question is the one that counts. Getting one wrong here is how the lesson sticks.