Python supports a number of built-in types and operations. This section covers the most common types, but information about additional types is available here.
A type, by the way, to a computer is a pair of a domain (e.g., the real numbers) and a set of operations (e.g., addition, multiplication) on them.
That may sound very mathematical, but there's an important message: by choosing a type you're determining if operators and function work on them and what they do.
The basic data numeric types are similar to those found in other languages, including:
i = 1 j = 219089 k = -21231
print(i, j, k)
Note that this is a point where python2 and python3 differ: python2 will output (1, 219089, -21231) here, python3 1 219089 -21231 In the jargon: python3 has made print a function, where it's been a statement in python2.
-> Here the brackets had a different meaning in python2.
Floating point values (
a = 4.3 b = -5.2111222 c = 3.1e33
print(a, b, c)
Complex values (
d = complex(4., -1.)
Manipulating these behaves the way you would expect, so an operation (
**, etc.) on two values of the same type produces another value of the same type (with one, exception,
/, see below), while an operation on two values with different types produces a value of the more 'advanced' type:
Adding two integers gives an integer:
1 + 3
Multiplying two floats gives a float:
3. * 2.
Subtracting two complex numbers gives a complex number:
complex(2., 4.) - complex(1., 6.)
Multiplying an integer with a float gives a float:
3 * 9.2
Multiplying a float with a complex number gives a complex number:
2. * complex(-1., 3.)
Multiplying an integer and a complex number gives a complex number:
8 * complex(-3.3, 1)
However, the division of two integers gives a float:
3 / 2
Note that in Python 2.x, this used to return
1 because it would round the solution to an integer. If you ever need to work with Python 2 code, the safest approach is to add the following line at the top of the script:
from __future__ import division
and the division will then behave like a Python 3 division. Note that in Python 3 you can also specifically request integer division:
3 // 2
The operator for raising one value to the power of another is
**. Try calculating $4^3$, $2+3.4^2$, and $(1 + i)^2$. What is the type of the output in each case, and does it make sense?
# enter your solution here
str) are sequences of characters:
s = "roof tile roof roof" print(s)
You can use either single quotes (
'), double quotes (
"), or triple quotes (
""") to enclose a string (the last one is used for multi-line strings). To include single or double quotes inside a string, you can either use the opposite quote to enclose the string:
or you can escape them:
You can access individual characters or chunks of characters using the item notation with square brackets
Note that in Python, indexing is zero-based, which means that the first element in a list is zero:
Note that strings are immutable, that is you cannot change the value of certain characters without creating a new string:
s = 'r'
You can easily find the length of a string:
You can use the
+ operator to combine strings:
"hello," + " " + "world!"
Finally, strings have many methods associated with them, here are a few useful examples:
s.upper() # An uppercase version of the string
s.index('tile') # An integer giving the position of the sub-string
s.split() # Split the string into a list of smaller strings
s.count(x) # Count the number of times x appears in the string
s.replace('roof','floor') # Will print a new string after replacing the word 'roof' with 'floor' in string s.
There are several kinds of ways of storing sequences in Python, the simplest being the
list, which is simply a sequence of any Python object.
li = [4, 5.5, "roof"]
Accessing individual items is done like for strings
Values in a list can be changed, and it is also possible to append or insert elements:
li = -2.2
As for strings, you can find the length of a list (the number of elements) with the
We already mentioned above that it is possible to access individual elements from a string or a list using the square bracket notation. You will also find this notation for other object types in Python, for example tuples or Numpy arrays, so it's worth spending a bit of time looking at this in more detail.
In addition to using positive integers, where
0 is the first item, it is possible to access list items with negative indices, which counts from the end:
-1 is the last element,
-2 is the second to last, etc:
li = [4, 67, 4, 2, 4, 6]
You can also select slices from a list with the
start:end:step syntax. Be aware that the last element is not included!
li[:2] # ``start`` defaults to zero
li[2:] # ``end`` defaults to the last element
li[::1] # specify a step size
Finally, you can sort a list by typing:
li.sort() print (li)
or in reverse order:
li.reverse() print (li)
Alphabetical sorting also works with text:
my_text_string = ['John Cleese','Terry Gilliam','Eric Idle','Terry Jones','Michael Palin'] my_text_string.sort() print(my_text_string)
my_text_string.append('Graham Chapman') # Add the missing Monty Python member to our list using .append my_text_string.sort() print (my_text_string)
Given a string such as the one below, make a new string that does not contain the word
a = "Hello, roof world!" # enter your solution here
Try changing the string above to see if your solution works (you can assume that
roof appears only once in the string).
Most things in Python are objects. But what is an object?
Every constant, variable, or function in Python is actually a object with a
type and associated attributes and methods. An attribute a property of the
object that you get or set by giving the
<object_name>.<attribute_name>, for example
img.shape. A method is a function that the object provides, for example
Use tab completion in IPython to inspect objects and start to understand attributes and methods. To start off create a list of 4 numbers:
li = [3, 1, 2, 1] li.<TAB>
This will show the available attributes and methods for the Python list
<TAB>-completion and help is a very efficient way to learn and later
remember object methods!
In : li. li.append li.copy li.extend li.insert li.remove li.sort li.clear li.count li.index li.pop li.reverse
If you want to know what a function or method does, you can use a question mark
In : li.append? Type: builtin_function_or_method String Form:<built-in method append of list object at 0x1027210e0> Docstring: L.append(object) -> None -- append object to end
In the following string, find out (with code) how many times the letter "A" appears.
s = "CAGTACCAAGTGAAAGAT" # your solution here
Given two lists, try making a new list that contains the elements from both previous lists:
a = [1, 2, 3] b = [4, 5, 6] # your solution here
Note that there are several possible solutions!
One final note on Python types: if you know languages like C, Java or, say, Pascal, you will remember you had to declare variables. Essentially, types are bound to names in such “statically typed” languages. In Python, on the other hand, types sit on the values, and names just point there; there's nothing that keeps you from having a single name point to differently typed values (except perhaps common sense in many cases). Jargon calls this dynamic typing.
a = 1 type(a)
a = 2.3 type(a)
a = 'hello' type(a)
There may be cases where you want to convert a string to a floating point value, and integer to a string, etc. For this, you can simply use the
int('5') + float('4.31')
is different from:
'5' + '4.31'
str(3) + str(4)
Be aware of this for example when connecting strings with numbers, as you can only concatenate identical types this way:
'The value is ' + 3
'The value is ' + str(3)