Representing Integers
00:01 Representing integers in Python. Firstly, a quick refresher. What is an integer? An integer is a whole number. By whole number we mean it has no fractional or decimal component.
00:16
An integer can be stored using different types. Two possible Python datatypes representing an integer are firstly str
. Secondly, an int
. Let’s take a look at those.
00:29
Firstly, you can represent an integer using a string literal using the notation shown below. You can say it’s been assigned with "110"
in quotes.
00:38 This could be single or double quotes. Here, Python understands you want to store the integer 110 as a string. You can do the same with the integer data type as seen here.
00:49
Notice there are no quotes around the number. It’s important to consider what you specifically mean by "110"
in quotes and 110
without the quotes in the examples above. As a human who’s used the decimal number system for your whole life, it might be obvious to you that you mean the number 110. However, there are several other number systems such as binary and hexadecimal, which use different bases to represent an integer.
01:17 Let’s take a look at that base system, using the Python REPL. Here I’m going to be using be bpython as it color codes the output, but the standard Python REPL will work in exactly the same way.
01:31 So we’ve assumed that the numbers one (1), one (1), zero (0) mean decimal 110. But in Python we can prefix this number with different codes to tell Python to use different number bases.
01:43
So by typing 0b
(zero b) before our number, we can see this actually represents 6 in binary. We have one, four, one, two, and no units. Doing the same in octal with an o
(0o
) leads us to the value of 72.
02:02
As we have one 64, one eight, and again, no units. Doing the same in hexadecimal with an x
(0x
) gives us the value 272. Here we have one 256, a 16. And once more, no units.
02:22
If there’s no prefix present int()
will assume that the number will be decimal.
02:30 Placing the prefix allows it to understand the number that we want.
02:38 However, if we don’t use the prefix, we’ll generate a syntax error.
02:49 String representations do not suffer from this…
03:02 because strings hold arbitrary text data. Now that you have some foundational knowledge about how to represent integers using string and int data types, you’l learn how to convert a Python string to an int.
Become a Member to join the conversation.