Types¶
We have seen that Python objects have a 'type':
type(5)
Floats and integers¶
Python has two core numeric types, int
for integer, and float
for real number.
one = 1
ten = 10
one_float = 1.0
ten_float = 10.
Zero after a point is optional. But the Dot makes it a float.
tenth= one_float / ten_float
tenth
type(one)
type(one_float)
The meaning of an operator varies depending on the type it is applied to! (And on the python version.)
print(one // ten)
one_float / ten_float
print(type(one / ten))
type(tenth)
The divided by operator when applied to floats, means divide by for real numbers. But when applied to integers, it means divide then round down:
10 // 3
10.0 / 3
10 / 3.0
So if I have two integer variables, and I want the float
division, I need to change the type first.
There is a function for every type name, which is used to convert the input to an output of the desired type.
x = float(5)
type(x)
10 / float(3)
I lied when I said that the float
type was a real number. It's actually a computer representation of a real number
called a "floating point number". Representing $\sqrt 2$ or $\frac{1}{3}$ perfectly would be impossible in a computer, so we use a finite amount of memory to do it.
N = 10000.0
sum([1 / N] * int(N))
Strings¶
Python has a built in string
type, supporting many
useful methods.
given = "Terry"
family = "Jones"
full = given + " " + family
So +
for strings means "join them together" - concatenate.
print(full.upper())
As for float
and int
, the name of a type can be used as a function to convert between types:
ten, one
print(ten + one)
print(float(str(ten) + str(one)))
We can remove extraneous material from the start and end of a string:
" Hello ".strip()
Note that you can write strings in Python using either single (' ... '
) or double (" ... "
) quote marks. The two ways are equivalent. However, if your string includes a single quote (e.g. an apostrophe), you should use double quotes to surround it:
"Terry's animation"
And vice versa: if your string has a double quote inside it, you should wrap the whole string in single quotes.
'"Wow!", said John.'
Lists¶
Python's basic container type is the list
.
We can define our own list with square brackets:
[1, 3, 7]
type([1, 3, 7])
Lists do not have to contain just one type:
various_things = [1, 2, "banana", 3.4, [1,2] ]
We access an element of a list with an int
in square brackets:
various_things[2]
index = 0
various_things[index]
Note that list indices start from zero.
We can use a string to join together a list of strings:
name = ["Sir", "Michael", "Edward", "Palin"]
print("==".join(name))
And we can split up a string into a list:
"Ernst Stavro Blofeld".split(" ")
"Ernst Stavro Blofeld".split("o")
And combine these:
"->".join("John Ronald Reuel Tolkein".split(" "))
A matrix can be represented by nesting lists -- putting lists inside other lists.
identity = [[1, 0], [0, 1]]
identity[0][0]
... but later we will learn about a better way of representing matrices.
Ranges¶
Another useful type is range, which gives you a sequence of consecutive numbers. In contrast to a list, ranges generate the numbers as you need them, rather than all at once.
If you try to print a range, you'll see something that looks a little strange:
range(5)
We don't see the contents, because they haven't been generatead yet. Instead, Python gives us a description of the object - in this case, its type (range) and its lower and upper limits.
We can quickly make a list with numbers counted up by converting this range:
count_to_five = range(5)
print(list(count_to_five))
Ranges in Python can be customised in other ways, such as by specifying the lower limit or the step (that is, the difference between successive elements). You can find more information about them in the official Python documentation.
Sequences¶
Many other things can be treated like lists
. Python calls things that can be treated like lists sequences
.
A string is one such sequence type.
Sequences support various useful operations, including:
- Accessing a single element at a particular index:
sequence[index]
- Accessing multiple elements (a slice):
sequence[start:end_plus_one]
- Getting the length of a sequence:
len(sequence)
- Checking whether the sequence contains an element:
element in sequence
The following examples illustrate these operations with lists, strings and ranges.
print(count_to_five[1])
print("Palin"[2])
count_to_five = range(5)
count_to_five[1:3]
"Hello World"[4:8]
len(various_things)
len("Python")
name
"Edward" in name
3 in count_to_five
Unpacking¶
Multiple values can be unpacked when assigning from sequences, like dealing out decks of cards.
mylist = ['Hello', 'World']
a, b = mylist
print(b)
range(4)
zero, one, two, three = range(4)
two
If there is too much or too little data, an error results:
zero, one, two, three = range(7)
zero, one, two, three = range(2)
Python provides some handy syntax to split a sequence into its first element ("head") and the remaining ones (its "tail"):
head, *tail = range(4)
print("head is", head)
print("tail is", tail)
Note the syntax with the *. The same pattern can be used, for example, to extract the middle segment of a sequence whose length we might not know:
one, *two, three = range(10)
print("one is", one)
print("two is", two)
print("three is", three)