Python Tutorial
Python Tutorial
help(“print”)
Exercise
In [1]: sqrt(2)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-40e415486bd6> in <module>()
----> 1 sqrt(2)
In [3]: math.sqrt(2)
Out[3]: 1.4142135623730951
The print Statement
>>> x = 12
>>> y = " lumberjack "
>>> x
12
>>> y
’ lumberjack ’
Object types in Python
• Atomic: numbers, booleans (true, false), …
• Container: (contains other elements)
– Sequences:
• Strings: “Hello World!”
• Lists: [1, 2, “three”]
• Tuples: (1, 2, “three”)
– Sets: {'a', 'b', 'c'}
– Dictionaries: {“R”: 51, “Python”: 29}
Object types in Python with
numpy module
• Container:
– Vectors and matrices:
array([[1, 2, 3],
[4, 5, 6]])
Object types in Python with
Pandas module
• Container:
– Dataframes:
In [18]: 3 == 3
In [26]: (3 == 3) and (3 < 4)
Out[18]: True
Out[26]: True
In [19]: 3 == 4
In [27]: (3 == 3) or (3 < 4)
Out[19]: False
Out[27]: True
In [20]: 3 < 4
In [28]: not((3 == 3) or (3 < 4))
Out[20]: True
Out[28]: False
In [21]: "aa" < "bb"
Out[21]: True
Booleans
• Notes:
– 0 and None are false
– Everything else is true
– True and False are just aliases for 1 and 0 respectively
Object types in Python
• Atomic: numbers, booleans (true, false), …
• Container:
– Sequences:
• Strings: “Hello World!”
• Lists: [1, 2, “three”]
• Tuples: (1, 2, “three”)
– Sets: {'a', 'b', 'c'}
– Dictionaries: {“R”: 51, “Python”: 29}
String Literals
• They can be defined either with double quotes (“) or single quotes (‘)
• + is overloaded to do concatenation
>>> x = 'hello'
>>> x = x + ' there'
>>> x
'hello there'
String Literals: multi-line
>>> print s
I’m a string
though I am much longer
than the others :)‘
Strings: some functions
In [56]: x = 'ABCDEF'
In [57]: len(x)
Out[57]: 6
In [58]: str(10.1)
Out[58]: '10.1'
Strings: some functions
• Some string functions are available only within a module, and
the dot (.) notation must be used (similarly to math.sqrt()).
The module for strings is called str. This module is imported
automatically by the system.
• For instance, lower() and upper() are two such functions:
In [73]: x = 'It was the best of times, it was the worst of times‘
In [73]: x = 'It was the best of times, it was the worst of times'
In [77]: str.count(x, 'was') # count counts how many times ‘was’ appears in x
Out[77]: 2
In [79]: print(str.split(x, ' ')) # split splits string x with space ‘ ‘ separator
['It', 'was', 'the', 'best', 'of', 'times,', 'it', 'was', 'the', 'worst', 'of', 'times']
In [80]: str.replace(x, 'was', 'is') # replace replaces ‘was’ by ‘is’ wherever it appears in x
Out[80]: 'It is the best of times, it is the worst of times'
String functions
• Typically, if you can call a function as module.function(object, other
arguments), you can also use another equivalente (but shorter) syntax:
object.function(other arguments)
• That is, there are two different (but equivalent) ways:
1. object.function(arguments)
2. module.function(object, arguments) # We already know this one
• Examples:
In [33]: x.lower() In [36]: x.upper()
Out[33]: 'it was the best of times, Out[36]: 'IT WAS THE BEST OF TIMES,
it was the worst of times‘ IT WAS THE WORST OF TIMES‘
• Examples:
In [39]: x.count('was') In [45]: x.replace('was', 'is')
Out[39]: 2 Out[45]: 'It is the best of times, it is the worst of times'
In [39]: x.count('was') a) Notice that the first way is shorter and you don’t
Out[39]: 2 need to remember the name of the module (str)
b) Only those methods listed with dir(‘was’) can be
In [40]: # is equivalent to
used
In [41]: str.count(x, 'was')
Out[41]: 2
Exercise: string functions
• Split a sentence x using both syntax cases:
– First case: using split as a function of x (x.split)
– Second case: using split as a function of module str (str.split(x))
Substrings (slicing)
indices
Negative -6 -5 -4 -3 -2 -1
indices
Positive 0 1 2 3 4 5
indices
Negative -6 -5 -4 -3 -2 -1
indices
s ‘0’ ‘1’ ‘2’ ‘3’ ‘4’ ‘5’
string2 ‘A’ ‘B’ ‘C’ ‘D’ ‘E’ ‘F’
>>> s = '012345'
>>> s[0:4:2] Get indices from 0 to 3 by 2 (even indices)
‘02'
>>> s[0::2] Get indices from 0 to end by 2 (even indices)
‘024'
>>> s[-1::-1] Get indices from end to beginning by -1
‘543210’ (reverse order)
>>> s[-1::-2] Get indices from end to beginning by -2
‘531' (indices 5, 3, 1 (or equivalently -1, -3, -5)
Exercise
1. Create any string, for instance:
‘In a village of La Mancha, the name of which I have no
desire to call to mind’
2. Convert it to uppercase:
'IN A VILLAGE OF LA MANCHA, THE NAME OF WHICH I
HAVE NO DESIRE TO CALL TO MIND'
3. Obtain another string by keeping one character
every four characters (via slicing):
'I L LAAHAOH ANEE L D'
Exercise: solution
In [76]: x = 'In a village of La Mancha, the name of which I have no desire to call to mind'
In [77]: x = x.upper()
In [78]: x
Out[78]: 'IN A VILLAGE OF LA MANCHA, THE NAME OF WHICH I HAVE NO
DESIRE TO CALL TO MIND'
In [79]: y = x[0::4]
In [80]: y
Out[80]: 'I L LAAHAOH ANEE L
String Formatting (1): %
• Similar to C’s printf
• <formatted string> % <elements to insert>
• Can usually just use %s for everything, it will convert the
object to its String representation.
In [7]: x = [0, 1, 2, 3, 4, 5]
In [8]: y = x
In [9]: x[1:3] = ['one', 'two', 'three']
In [10]: x
Out[10]: [0, 'one', 'two', 'three', 3, 4, 5]
In [11]: y
Out[11]: [0, 'one', 'two', 'three', 3, 4, 5]
Lists: Modifying Content
In [20]: y = [1, 2, 3]
• + also concatenates lists, but it In [21]: y + [13, 14]
does not modify the original list Out[21]: [1, 2, 3, 13, 14]
In [22]: y
Out[22]: [1, 2, 3]
Reminder: two ways of calling
functions on objects
• Let us remember that there are two ways of applying functions to
lists (just as with strings):
1. module.function(object, …)
2. object.method(…)
In [27]: x = [1, 2, 3]
In [28]: list.extend(x, [13, 14])
In [29]: x
Out[29]: [1, 2, 3, 13, 14]
# is equivalent to:
In [30]: x = [1, 2, 3]
In [31]: x.extend([13, 14])
In [32]: x
Out[32]: [1, 2, 3, 13, 14]
Lists: deleting elements
• Function del:
In [33]: x = range(10)
In [34]: x
Out[34]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [35]: del(x[1])
In [36]: x
Out[36]: [0, 2, 3, 4, 5, 6, 7, 8, 9]
In [37]: del(x[2:4])
In [38]: x
Out[38]: [0, 2, 5, 6, 7, 8, 9]
Object types in Python
• Atomic: numbers, booleans (true, false), …
• Compound:
– Sequences:
• Strings: “Hello World!”
• Lists: [1, 2, “three”]
• Tuples: (1, 2, “three”)
– Sets: {'a', 'b', 'c'}
– Dictionaries: {“R”: 51, “Python”: 29}
Tuples
• Tuples are immutable
versions of lists
• One strange point is the >>> x = (1,2,3)
format to make a tuple with >>> x[1:]
(2, 3)
one element:
>>> y = (2,)
‘,’ is needed to differentiate >>> y
from the mathematical (2,)
expression (2) >>>
Object types in Python
• Atomic: numbers, booleans (true, false), …
• Compound:
– Sequences:
• Strings: “Hello World!”
• Lists: [1, 2, “three”]
• Tuples: (1, 2, “three”)
– Sets: {'a', 'b', 'c'}
– Dictionaries: {“R”: 51, “Python”: 29}
Dictionaries
• A set of key-value pairs
• Dictionaries are mutable
• Example number of bottles of different drinks
• Access and modification by key
In [47]: d = {'milk': 3, 'beer': 21, 'olive oil':
2}
In [48]: d
Out[48]: {'beer': 21, 'milk': 3, 'olive oil': 2}
In [49]: d['milk']
Out[49]: 3
In [50]: d['milk'] = 4
In [51]: d
Out[51]: {'beer': 21, 'milk': 4, 'olive oil': 2}
Dictionaries: Add/Delete
• Assigning to a key that does not exist adds an entry:
In [52]: d['coffee'] = 3
In [53]: d
Out[53]: {'beer': 21, 'coffee': 3, 'milk': 4, 'olive oil': 2}
In [54]: del(d['beer'])
In [55]: d
Out[55]: {'coffee': 3, 'milk': 4, 'olive oil': 2}
Copying Dictionaries and Lists
• The built-in list >>> l1 = [1] >>> d = {1 : 10}
function will >>> l2 = list(l1) >>> d2 = d.copy()
copy a list >>> l1[0] = 22 >>> d[1] = 22
>>> l1 >>> d
• The dictionary [22] {1: 22}
has a method >>> l2 >>> d2
called copy [1] {1: 10}
Data Type Summary
This is code
Markdown
• Markdown is a language to format text:
– *this goes in italics*
– **this goes in boldface**
– #This is a header
– ##This is a subheader
– I can even write equations (in LaTeX):
• $\sqrt{\frac{x}{x+y}}$
This is a list:
- Cheese
- Wine
- Jam
You can even embed plots
Saving the notebook
Download the notebook
• In several formats: (filename can be changed in File/Rename)
– Python notebook: it can be loaded again as a notebook
– Python script: this is a text file containing the sequence of Python commands.
Text is also stored as comments (#)
– html: it can be loaded later in a browser
– pdf (it might not work because it requires LaTeX)
Etc.
• In order to finish the notebook:
– File / close and halt
• Jupyter notebooks have more options but
you can explore them yourselves
Exercise
• Try to get something similar to:
HINT
Topics
1. If … then … else
2. Loops:
– While condition …
– For …
3. Functions
4. High-level functions (map, filter, reduce)
If Statements
if condition : if condition :
sentence1 sentence1
sentence2 sentence2
Example:
… …
Indentation
next sentence elif condition3 :
sentencea
if condition : sentenceb
sentence1 …
sentence2 else :
… sentencex
else : sentencey
sentencea … Sentence that
sentenceb next sentence follows the
… “if” (outside
next sentence of the “if”
block) Result is: ?
If Statements
Example:
Result is: y = 60
Note on indentation
• Python uses indentation instead of
braces (or curly brackets) to Example:
determine the scope of expressions Indentation
• All lines must be indented the same
amount to be part of the scope (or
indented more if part of an inner
scope)
• This forces the programmer to use
proper indentation since the
indenting is part of the program! Sentence that
follows the
• Indentation made of four spaces is “if” (outside
recommended of the “if”
block)
While Loops
While condition is true, execute sentences in the while block
(sentence1, sentence2, …)
while condition :
sentence1
sentence2
…
Next sentence
(outside while block)
For Loops
variable takes succesive values in the sequence
for variable in sequence :
sentence1
sentence2
…
Next sentence (outside for block)
Exercise
• Create a list of numbers [0, 1, 3, 4, 5, 6]
• Iterate over this list by using a for loop
– For each element in the list, print “even” if the
number is even and “odd” if the number is odd
• Reminder: a number x is even if the
remainder of the division by 2 is zero. That
is: (x % 2 == 0)
• Once you are done, try with another list:
[1, 7, 3, 2, 0]
Solution
Function Definition
“return x” returns the value and ends the function exectution