Download Functions in Python! - Machine Learning @ Leuphana Lüneburg

Document related concepts
no text concepts found
Transcript
Functions in Python!
Maryam Tavakol
Machine Learning Group
Winter semester 2016/17
1
Functions
•
To make calculations
•
Easy to reuse
•
Easier to read calculations
2
Built-in functions
>>> abs(-9) # function call
9
>>> abs(3.3)
3.3
3
Function call
«function_name» («arguments»)
•
Arguments are the value that is passed to a function.
•
A function usually returns a value as well.
4
Function call
•
Can use return value in expression.
>>> abs(-7) + abs(3.3)
10.3
5
Function call
•
use function calls as arguments to other functions:
>>> pow(abs(-2) + round(4.3))
16
6
Convert types
>>> int(34.6)
34
>>> int(-4.3)
-4
>>> float(21)
21
7
Define functions
>>> def convert_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5 / 9
>>> convert_to_celsius(80)
26.6666666
8
Define functions
def «function_name» («arguments»):
«block»
9
Local variables
• Some computations are complex, and breaking them down into separate steps
can lead to clearer code.
>>> def quadratic(a, b, c, x):
first = a * x ** 2
second = b * x
third = c
return first + second + third
• Variables like first, second, and third that are created within a function are called
local variables
Local variables
• Local variables get created each time that function is called.
• They are erased when the function returns
• They can’t be used outside of the function, Because they only exist when the
function is being executed
• A function’s parameters are also local variables
Tracing Function Calls
>>> def f(x):
x=2*x
return x
>>> x = 1
>>> x = f(x + 1) + f(x + 2)
Confusing?
Tracing Function Calls
• Whenever Python executes a function call, it creates a namespace in which to
store local variables for that call.
• Python keeps another namespace for variables created in the shell
• Evaluate the arguments left to right
Tracing Function Calls
>>> x = 1
Tracing Function Calls
>>> x = f(x + 1) + f(x + 2)
Tracing Function Calls
>>> def f(x):
Tracing Function Calls
>>> def f(x):
x=2*x
Tracing Function Calls
>>> def f(x):
x=2*x
return x
Tracing Function Calls
Similarly, the same thing happens for the next call.
Designing New Functions
1. Examples
2. Type contract
3. Header
4. Description
5. Body
6. Test
More detail in the text book!
Writing and Running a Program
1. Create a new file with “.py” as the extension
2. python file_name.py
Text in Python!
Maryam Tavakol
Machine Learning Group
Winter semester 2016/17
22
String
Sequence of character
>>> ‘Aristotle’
‘Aristotle’
>>> “Aristotle”
‘Aristotle’
Operations on Strings
• Len:
len(‘abc’) # 3
• concatenation of strings:
‘abc’ + ‘efg’ # ‘abcefg’
• Common mistake: ‘abc’ + 3 # TypeError: Can't convert 'int' object to str implicitly
‘abc’ + str(3) # ‘abc3’
• Replication:
‘abc’ * 3 # ‘abcabcabc’
Special character
• 'that's not going to work' # SyntaxError: invalid syntax
• "that's better" # "that's better"
• 'She said, "That is better."' #'She said, "That is better."'
• 'She said, "That' + "'" + 's hard to read."' # 'She said, "That\'s hard to read."'
Multiline String
>>> '''one
two
three'''
'one\ntwo\nthree'
print
• Print information on screen but no color and no format
>>> print(‘abc’)
abc
>>> print(1)
1
>>> print(1,’abc’)
1
abc
input
• Read from keyboard, always return string
>>> species = input()
Homo sapiens
>>> species
'Homo sapiens'
Control structure in
Python!
Maryam Tavakol
Machine Learning Group
Winter semester 2016/17
29
Recap- relational operation
• Already seen boolean operation and comparison(relational) operation.
• We can combine them in various ways
>>> (1 < 2) and ( 2 < 4)
True
>>> 1 < 2 < 4 #chain comparison
True
>>> 3 < 5 != True # equivalent to: (3 < 5) and (5 != True)
True
• 5 is neither True nor False
Short-Circuit Evaluation
>>> 1 / 0 # ZeroDivisionError: division by zero
>>> (2 < 3) or (1 / 0)
True
• Since the operation is “or”, as soon as interpreter realize that the first operand is
True, it would ignore the other operand and returns True.
• Same situation for “and”. If the first operand is False, interpreter returns False no
matter what the other one is.
Comparing Strings
>>> 'A' < 'a'
True
>>> 'A' > 'z'
False
>>> 'abc' < 'abd'
True
>>> 'abc' < 'abcd'
True
>>> 'Jan' in '01 Jan 1838' # check if the left operand exists in the second operand
True
if statement
If <<condition>>:
<<block>>
• Condition is a boolean expression
• Block is a block of code like function body
>>> if 1 > 0:
print(“TRUE”)
TRUE
elseif extension
If <<condition>>:
<<block>>
elif <<condition>>:
<<block>>
else:
<<block>>
>>> if 5 > 7:
print(“5>7!”)
elif 5>6:
print(“5>7!”)
else:
print(“none”)
none
Nested if statement
if <<condition>>:
if <<condition>>:
<<block>>
elif <<condition>>:
<<block>>
Program organization in Python!
Maryam Tavakol
Machine Learning Group
Winter semester 2016/17
36
Modules
• A module is a collection of variables and functions that are grouped together in a
single file.
• The variables and functions in a module are usually related to one another in
some way
math module
>>> import math
>>> type(math)
<class 'module'>
>>> math.sqrt(9)
3.0
>>> math.pi
3.141592653589793
Alternative way to import module
>>> from math import sqrt, pi
>>> sqrt(9)
3.0
>>> from math import *
>>> print(sqrt(8))
2.8284271247461903
Define new module
1. Create a new file with “.py” as the extension
2. Define new functions in there
That’s it!
You can later import the module using the filename without the “.py” extension and
call the function you have defined in there.
Import new module
>>> import temperature
>>> celsius = temperature.convert_to_celsius(33.3)
>>> temperature.above_freezing(celsius)
True
Look inside of import
>>> import new_module
I am a new module
>>> import new_module
>>>
Note:
• Python executes modules as it imports them
• Python loads modules only the first time they’re imported.
new_module.py
print(“I am a new
module”)
Which Code Gets Run on import
• Special python variable called __name__
• Two way to execute python module:
• Import module: the value of __name__ is the module’s name
• Run module: the value of __name__ is “__main__”
if __name__ == "__main__":
print("I am the main program.")
else:
print("Another module is importing me.")
Methods in Python!
Maryam Tavakol
Machine Learning Group
Winter semester 2016/17
44
Methods
• A method is another kind of function that is attached to a particular type.
• Every type has its own set of methods
Type: str
>>> help(str)
Help on class str in module builtins:
class str(object)
| str(object[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
....
Type: str
….
|
| Methods defined here:
|
| __add__(...)
|
x.__add__(y) <==> x+y
|
| __contains__(...)
|
x.__contains__(y) <==> y in x
….
Type: str
.....
| capitalize(...)
|
S.capitalize() -> str
|
|
Return a capitalized version of S, i.e. make the first character
|
have upper case and the rest lower case.
|
| count(...)
|
S.count(sub[, start[, end]]) -> int
....
Type: str
>>> str.capitalize('browning')
'Browning'
>>> 'browning'.capitalize() # OO style of calling methods
'Browning'
Method call chains
Underscores
….
|
| Methods defined here:
|
| __add__(...)
|
x.__add__(y) <==> x+y
|
| __contains__(...)
|
x.__contains__(y) <==> y in x
….
Special syntax:
>>> 'TTA' + 'GGG'
'TTAGGG'
>>> 'TTA'.__add__('GGG')
'TTAGGG'
Class vs. Module
• Classes are like modules, except that classes contain methods and modules
contain functions.
• Methods are like functions, except that the first argument must be an object of
the class in which the method is defined.
• Method calls in this form—'browning'.capitalize()—are shorthand for this:
str.capitalize('browning').
• Methods beginning and ending with two underscores are considered special by
Python, and they are triggered by particular syntax
Lists in Python!
Maryam Tavakol
Machine Learning Group
Winter semester 2016/17
53
Lists
Storing Collections of Data
>>> whales = [5, 4, 7, 3, 2, 3, 2, 6, 4, 2, 1, 7, 1, 3]
>>> whales
[5, 4, 7, 3, 2, 3, 2, 6, 4, 2, 1, 7, 1, 3]
Access to list members
>>> whales = [5, 4, 7, 3, 2, 3, 2, 6, 4, 2, 1, 7, 1, 3]
>>> whales[0]
5
>>> whales[1]
4
>>> whales[12]
1
>>> whales[13]
3
>>> whales[1001] # IndexError: list index out of range
Access to list members
>>> whales = [5, 4, 7, 3, 2, 3, 2, 6, 4, 2, 1, 7, 1, 3]
>>> whales[-1]
3
>>> whales[-2]
1
>>> whales[-14]
5
>>> whales[-15] # IndexError: list index out of range
More on lists
• Empty List
>>> whales = []
• Heterogeneous List
>>> krypton = ['Krypton', 'Kr', -157.2, -153.4]
>>> krypton[1]
'Kr'
>>> krypton[2]
-157.2
List operations
List operators- + and *
>>> original = ['H', 'He', 'Li']
>>> final = original + ['Be']
>>> final
['H', 'He', 'Li', 'Be']
>>> metals = ['Fe', 'Ni']
>>> metals * 3
['Fe', 'Ni', 'Fe', 'Ni', 'Fe', 'Ni']
List operators- del and in
>>> metals = ['Fe', 'Ni']
>>> del metals[0]
>>> metals
['Ni']
>>> [1, 2] in [0, 1, 2, 3]
False
List operators- Slicing
>>> celegans_phenotypes = ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma']
>>> useful_markers = celegans_phenotypes[0:4]
List operators- Slicing
>>> celegans_phenotypes = ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma']
>>> celegans_phenotypes[:4]
['Emb', 'Him', 'Unc', 'Lon']
>>> celegans_phenotypes[4:]
['Dpy', 'Sma']
List operators- Slicing
>>> celegans_phenotypes = ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma']
>>> celegans_copy = celegans_phenotypes[:]
>>> celegans_phenotypes[5] = 'Lvl'
>>> celegans_phenotypes
['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Lvl']
>>> celegans_copy
['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma']
List operators- Slicing
Altering list
>>> nobles = ['helium', 'none', 'argon', 'krypton', 'xenon', 'radon']
Altering list
>>> nobles[1] = 'neon'
More on altering variables (objects)
• Not all types are mutable.
• String and Int are immutable. You only change it by assigning it to a new value
>>> s = “abc”
>>> s[0]
a
>>> s[0] = ‘x’ # 'str' object does not support item assignment
Alias
• Two variables are said to be aliases when they contain the same memory
address
>>> celegans_phenotypes = ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma']
>>> celegans_copy = celegans_phenotypes[:]
Alias
>>> celegans_phenotypes = ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma']
>>> celegans_alias = celegans_phenotypes
>>> celegans_phenotypes[5] = 'Lvl'
>>> celegans_phenotypes
['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Lvl']
>>> celegans_alias
['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Lvl']
• Note: That happens because list are mutable!
Mutable parameters
• Aliasing occurs when you use list parameters as well, since parameters are
variables.
>>> def remove_last_item(L):
del L[-1]
return L
>>> celegans_markers = ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Lvl']
>>> remove_last_item(celegans_markers)
['Emb', 'Him', 'Unc', 'Lon', 'Dpy']
>>> celegans_markers
['Emb', 'Him', 'Unc', 'Lon', 'Dpy']
List methods
append
clear
count
extend
index
insert
pop
remove
reverse
sort
List of lists
>>> life = [['Canada', 76.5], ['United States', 75.5], ['Mexico', 72.0]]
List of lists
>>> life[0]
['United States', 75.5]
>>> life[1][0]
'United States'
Loops in Python!
Maryam Tavakol
Machine Learning Group
Winter semester 2016/17
74
Loop over list
for «variable» in «list»:
«block»
Example:
>>> For v in [1,2,3,4,5]:
print(v)
1
2
3
4
Loop over string
>>> country = 'United States of America'
>>> for ch in country:
if ch.isupper():
print(ch)
U
S
A
Loop over range of number
>>> for num in range(5):
print(num)
0
1
2
3
4
>>> range(5)
[0,1,2,3,4]
>>> range(1,5)
[1,2,3,4]
>>> range(1,6,2)
[1,3,5]
Loop over indices of a list
Happen so often that we need to loop over the indices of a list, not its values
>>> values = [4, 10, 3, 8, -6]
>>> for i in range(len(values)):
print(i)
0
1
2
3
4
Nested loops
>>> outer = ['Li', 'Na', 'K']
>>> inner = ['F', 'Cl', 'Br']
>>> for metal in outer:
for halogen in inner:
print(metal + halogen)
LiF
LiCl
LiBr
NaF
NaCl
NaBr
KF
KCl
KBr
Loop over nested lists
>>> elements = [['Li', 'Na', 'K'], ['F', 'Cl', 'Br']]
>>> for inner_list in elements:
print(inner_list)
['Li', 'Na', 'K']
['F', 'Cl', 'Br']
while loop
• Loop unit the condition is true
while «expression»:
«block»
>>> rabbits = 3
>>> while rabbits > 0:
print(rabbits)
rabbits = rabbits - 1
3
2
1
break statement
• We use break statement when we want to break out of the normal flow of the loop
(for or while).
>>> for i in range(10):
if i > 3:
break
print(i)
0
1
2
3
continue statement
We use break statement when we want to skip the rest of body and jump to the
next iteration of the loop (for or while)
>>> for i in range(5):
if i%2==0:
continue
print(i)
1
3