from IPython.display import Image
from IPython.display import clear_output
from IPython.display import FileLink, FileLinks
Values of different types stores different types of information.
Different types can be used with different operations, functions and methods.
1+2
"1"+"2"
"1"+2
"1"*2
Take extra care when comparing values
2<12
"2"<"12"
float("1")
int("1")
str(1)
int("2.2")
Converting between strings and lists
list("hello")
str(['h', 'e', 'l', 'l', 'o'])
''.join(['h', 'e', 'l', 'l', 'o'])
mylist = ["comedy", "drama", "drama", "sci-fi"]
mydict = {"genre": "drama", "title": "Toy Story"}
myset = set(mylist)
print('All genres', myset)
A named piece of code that performs a specific task.
A relation between input data (parameters) and a result (output data).
def
keywordreturn
Scope
a
def myfunc(a, b):
print(a)
a
a = 5
def myfunc(a):
a += 2
return a
b = myfunc(8)
a, b
a = 3
print('Globally, a is', a)
def myfunc(a):
print('In f, a is', a)
a += 2
print('Then a in f is', a)
return a
print('Calling f with argument 8')
b = myfunc(8)
print('Result of f(8) =', b)
print('Finally the global a is', a)
The local a
in myfunc
shadows the global a
.
The variables inside functions are local. To avoid confusion, use different variable names.
global_a = 3
def myfunc(value):
value += 2
return value
result = myfunc(8)
global_a, result
No confusion!
myfunc
has unique variable names.
Controlling loops - break
for x in lines_in_a_big_file:
if x.startswith('>'): # this is the only line I want!
do_something(x)
...waste of time!
for x in lines_in_a_big_file:
if x.startswith('>'): # this is the only line I want!
do_something(x)
break # break the loop
Controlling loops - continue
for x in lines_in_a_big_file:
if x.startswith('>'): # this is a comment
# just skip this! don't do anything
do_something(x)
for x in lines_in_a_big_file:
if x.startswith('>'): # this is a comment
continue # go on to the next iteration
do_something(x)
for x in lines_in_a_big_file:
if not x.startswith('>'): # this is *not* a comment
do_something(x)
Another control statement: pass - the placeholder
def a_function():
# I have not implemented this just yet
def a_function():
# I have not implemented this just yet
pass
a_function()
Returning nothing
def a_function():
pass
def b_function():
return
result_a = a_function()
result_b = b_function()
print('a:', result_a, 'b:', result_b)
None
¶Other keywords: True
, import
, and
What is None
? What type? Why?
When is it used?
True
, False
)None
¶NoneType
type(None)
None
¶None == True
None == False
value = None
if value:
print('value is something')
else:
print('no value!')
None
¶None <= 0
myvalue = None
if myvalue and myvalue <= 0:
print('The value is smaller than or equal to 0')
else:
print('The value is either None or greater to zero')
Keyword arguments
open('../files/250.imdb', 'r', encoding='utf-8')
def prettyprinter(name, value, delim=":"):
out = "The " + name + " is " + delim + " " + value + "."
return out
prettyprinter("title", "Movie")
def prettyprinter(name, value, delim=":"):
out = "The " + name + " is " + delim + " " + value + "."
return out
prettyprinter("genre", "Drama", "=")
prettyprinter("genre", "Drama", delim="=")
def prettyprinter(name, value, delim=":", end=None):
out = "The " + name + " is " + delim + " " + value
if end:
out += end
return out
my_str = prettyprinter("title", "Movie")
print(my_str)
prettyprinter("genre", "Drama", "=", ".")
prettyprinter("genre", "Drama", delim="=", end="!")
prettyprinter("genre", "Drama", end="!", delim=":::")
prettyprinter("genre", "Drama", end="!")
prettyprinter("genre", "Drama", delim="=", ".")
Positional arguments comes first, keyword arguments after!
open(file, mode='r', buffering=-1, encoding=None, errors=None,
newline=None, closefd=True, opener=None)
open('../files/250.imdb', 'r', encoding='utf-8')
open('../files/250.imdb', mode='r', encoding='utf-8')
open('../files/250.imdb', encoding='utf-8', mode='r')
→ Notebook Day_4_Exercise_1 (~30 minutes)
import sys
sys.argv[1]
Check out the module index
How to find the right module?
How to understand it?
How to find the right module?
How to understand it?
import math
help(math)
dir(math)
help(math.sqrt)
math.sqrt(3)
import math
math.sqrt(3)
import math as m
m.sqrt(3)
import math as c
counter = c.Counter()
from math import sqrt, ceil
sqrt(3)
import math
: standardimport xml.etree.ElementTree as ET
: for long namesfrom collections import defaultdict
: import only one function/class→ Notebook Day_4_Exercise_2 (~30 minutes)
Remember help()
?
Works because somebody else has documented their code!
def process_file(filename, chrom, pos):
for line in open(filename):
if not line.startswith('#'):
columns = line.split('\t')
if col[0] == chrom and col[1] == pos:
print(line)
?
def process_file(filename, chrom, pos):
"""
Reads a vcf file and prints the genotype of the samples
at chromosome chrom and position pos.
"""
for line in open(filename):
if not line.startswith('#'):
columns = line.split('\t')
if col[0] == chrom and col[1] == pos:
print(line)
help(process_file)
Your code may have two types of users:
Write documentation for both of them!
""" What does this function do? """
(doc strings)# implementation details
(comments)def process_file(filename, chrom, pos):
"""
Reads a vcf file and prints the genotypes of corresponding to
chromosome chrom and position pos.
"""
for line in open(filename):
if not line.startswith('#'): # skip comments
columns = line.split('\t') # file is tab separated
# Check if chrom and pos match
if col[0] == chrom and col[1] == pos:
# genotype starts at column index 9
print(col[9:])
At the beginning of the file
""" This module provides functions for..."""
For every function
def make_list(x): """ Returns an list of lenght x """
my_list[5] += other_list[3] # explain why you do this!```
Save your code in mymodule.py
Run it: python3 mymodule.py
Import it: >>> import mymodule
def main(input_str):
# do something
pass
# at the end of the file
if __name__ == "__main__":
result = main(sys.argv[1]) # get input from command line
print("The result is: ", result) # show result to user
main()
In file module.py
:
print("My name is " + __name__)
if __name__ == "__main__":
print("I'm run as a main module")
import module as m
But if we run the file module.py
as a script:
→ Notebook Day_4_Exercise_3 (~30 minutes)
Written by last year's teacher, Frédéric Haziza (slightly modified).
Lets you work with a database with information about real estate around Uppsala.
Have a look at the documentation and the the code!
class HomeEntry():
def __init__(self, row):
return self.raw_query(q)
function createPopup(feature) {
feature.popup = new OpenLayers.Popup.FramedCloud("pop",
...
You don't need to understand these things, as long as you can understand the documentation!
HomeEntry
home.get_price()
, home.get_location()
, home.get_area()
database = HomeDB('uppsala.sqlite')
database.connect()```
homes = db.select() # Get everything```
homes = db.select('price > 1000000') # Select by some criteria```
homes = db.select('id = "2447"')
```
plot()
creates a html file, which you can open in a browser.
plot(selection, # a list of homes to print
output='selection.html', # the name of the output file
special=None, # a very special house
zoom=12, # the zoom levl
latitude=59.83732598851705, # the center position (lat(
longitude=17.64549846959149, # the center position (long)
radius=5000) # circle radius
```
selection
output
special
Other useful functions
haversine()
sort_by_price()
→ Notebook Day_4_Exercise_4 (~60 minutes)
break
, continue
, pass
None
open(filename, encoding="utf-8")
help()
, """Doc string"""
, # comment