-
Notifications
You must be signed in to change notification settings - Fork 0
Chapter 4 (Types)
| Type | Name | Description | Example |
|---|---|---|---|
int |
Integer | Whole numbers |
1, -4
|
float |
Floating point | Numbers with a decimal point |
0.202, 1.0
|
bool |
Boolean | A logical value of either True or False only |
True, False
|
str |
String | An ordered sequence of characters |
"Hello!", "θοθ", "312"
|
NoneType |
None, or null | A null value | None |
...and many more...
But these four types are the most common ones that you will meet.
Python is a dynamically typed (or untyped) language (as opposed to statically typed ones), which means that variables do not have a pre-set type, and can change types throughout the code. This also means that the coder does not need to define the type upon instantiating it. In other words, something like
int a = 1is not just unnecessary in Python; it throws an error!>>> a = 1 >>> type(a) <class 'int'> >>> a = True >>> type(a) <class 'bool'>
These types should be quite familiar as you have seen them in earlier sections.
>>> a = 1
>>> type(a)
<class 'int'>
>>> a += 0.1
>>> a
1.1
>>> type(a)
<class 'float'>In the above example, you can see that when variables are instantiated as whole numbers, their assigned type is int. However, once operations (e.g. addition, multiplication) with variables of type float are performed on them, the original variable becomes a float too.
However, do note that all divisions result in a float output.
>>> type(4 / 2)
<class 'float'>This section should be the most logical. The only possible bool values are True and False!
Note that
TrueandFalsemust be capitalised!
There are still some things to introduce, though, and these are the boolean operators and, or, and not.
a |
b |
a and b |
a or b |
|---|---|---|---|
True |
True |
True |
True |
True |
False |
False |
True |
False |
True |
False |
True |
False |
False |
False |
False |
As for not we have:
>>> not True
False
>>> not False
TrueBoolean operators also follow similar left-to-right, parenthetical logic to arithmetic operators.
>>> not True and True
False
>>> not False or (True and False)
TrueStrings are a sequence of characters, which can include digits and non-Latin characters. To define a string, put whatever you want to say between double (or single, just be consistent) quotes, like this: "whatever you want to say".
Types are important!
>>> a = "3" >>> b = 3 >>> type(a) <class 'str'> >>> type(b) <class 'int'> >>> a + b Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> a + b TypeError: can only concatenate str (not "int") to strSee that we cannot add "3" with 3, as "3" is not of type
int; it is astr.
Concatenation is when you take one string and smoosh it with another one, using the + operator. You may also use print(..., ...). By separating the variables with a comma, they will be printed, separated by a space. This does not only work for strings, but variables of other types too. However, concatenation using + only works on strings.
>>> "a" + "b"
'ab'
>>> print("a", True, "b", 1)
a True b 1
>>> print("a" + True + "b" + 1)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
print("a" + True + "b" + 1)
TypeError: can only concatenate str (not "bool") to strOther than "adding" strings, you can also "multiply" them!
>>> "a" * 10
'aaaaaaaaaa'Strings are essentially an ordered list of characters, and each character can be given an index, which helps to identify its relative position in the string.
Let's say we have the String "python".
| p | y | t | h | o | n |
|---|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 4 | 5 |
| -6 | -5 | -4 | -3 | -2 | -1 |
>>> p = "python"
>>> len(p)
6
>>> p[0]
'p'
>>> p[4]
'o'
>>> p[-4]
't'What we have just done is access the characters by their positive and negative index numbers, as shown by the table. The first character has the index 0 (this is because of zero indexing, something used extensively in coding), while the last character may be accessed with 5 or -1 (which may be more useful). To get the length of a string, use len().
What if we want to access a bunch of characters, not just one?
>>> p[1:3]
'yt'
>>> p[:3]
'pyt'
>>> p[:-4]
'py'
>>> p[:-1]
'pytho'
>>> p[:]
'python'
>>> p[2:]
'thon'[x:y] denotes a slice, which returns the characters starting from x (inclusive) to the character right before y (exclusive). This may seem counterintuitive, but that's how coding is. You will see more of this inclusive lower bound and exclusive upper bound convention in loops, when you use range(). Also, when the lower or upper bound is not written (e.g. [:-1] or [2:]), we assume that the string starts/ends right from the start/end.
Wait! There's more...
>>> p[:4:2]
'pt'
>>> p[:-1:3]
'ph'There are three arguments for slicing, written like this: [start:stop:step]. Step tells you that the string slicing will occur every "step"-th character. For example, for p[:4:2], we extract the 0th letter, skip the 1st letter, get the 2nd letter, and once again skip the 3rd letter, thus obtaining "pt" ("p[y]t[h]"). You will see these three arguments when using range() too.
There is only one object that corresponds to this type: None! It is the value of empty variables, or the return value of functions that don't return anything. Nothing much.
The None value is different from 0, "", or False! None represents a value where there is nothing. It is like the answer to the question "What letter in the alphabet comes before A?"
Type casting converts the variable data type into another data type. There are two types of type casting: implicit and explicit.
Implicit type casting occurs when Python automatically converts the data type by inferring what the user wants.
>>> a = 1
>>> type(a)
<class 'int'>
>>> a += 0.1
>>> a
1.1
>>> type(a)
<class 'float'>This example was shown earlier. See that the type(a) was automatically converted to float after another float 0.1 was added to it.
Explicit type casting is performed by typing out certain functions to convert the type. Common type casting functions include: int(), float(), and str().
Wait... but since we already have implicit type casting, why would we ever need to explicitly convert the type?
Here's why:
>>> a = "3"
>>> b = 2
>>> a + b
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
a + b
TypeError: can only concatenate str (not "int") to str
>>> a + str(b)
'32'
>>> int(a) + b
5We cannot add a variable of type str with another of type int. However, by explicitly casting the type, we get either "32" (this is known as string concatenation, where additional strings are stuck onto the end of the previous one), or 5 (which is simply the addition of two variables of type int).
Beware of invalid (or seemingly invalid) type casting.
For example:
>>> int("1.1") Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> int("1.1") ValueError: invalid literal for int() with base 10: '1.1' >>> int(True) 1 >>> int(False) 0In Python,
Truehas an integer value of 1, whileFalsehas an integer value of 0. This may be useful when integrating booleans with arithmetic operations.
>>> float(1)
1.0
>>> int(1.1)
1
>>> int(1.999)
1
>>> int(-1.1)
-1
>>> int(-1.999)
-1
>>> int("1")
1
>>> int("1.1")
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
int("1.1")
ValueError: invalid literal for int() with base 10: '1.1'
>>> float("1.1")
1.1float(), when performed on an integer, simply converts it to a number with a decimal point. On the other hand, though, when int() is done on a float, converts its type to int, by ignoring everything after the decimal point. It is not the same as rounding up, down, or off! Nonetheless, it can still be useful sometimes.
Also, you can convert variables of type str to type int or float. However int("1.1") throws an error, so usually when dealing with numeric strings, use float().
By a team of students from NUS High School, aiming to make coding easier for everyone.