### Present Remotely

Send the link below via email or IM

CopyPresent to your audience

Start remote presentation- Invited audience members
**will follow you**as you navigate and present - People invited to a presentation
**do not need a Prezi account** - This link expires
**10 minutes**after you close the presentation - A maximum of
**30 users**can follow your presentation - Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

### Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.

You can change this under Settings & Account at any time.

# Python

Introduction to python

by

Tweet## Christoph Hartmann

on 16 October 2012#### Transcript of Python

Python 16.10.2012 What is python? Programming language

Paradigms: Object-oriented, imperative, functional

Scripting language (Interpreter, not a compiler)

Dynamic typing (example)

Indentation-based syntax Why python? Simple and powerful

Community-based, open source

Widespread use

Easily extendable

-> SQL, matlab, R support

Batteries included

Readable, compact syntax (Why not python? - slow.) Intermission - 3.3 vs 2.7 3.3 most recent version

3.3 backwards-incompatible (print ("x")) Still widespread use of 2.7

2.7 forwards-compatible (from __future__ import) We'll use 3.3 code compatible with 2.7 Functions Datatypes Control structures if

while

for for ... in ...: typical for python. Often more than one iteration possible: for i, x in enumerate(l): def starts a function

return returns variables

arguments follow in brackets

after function name

default arguments can be set using '='

use docstrings! (""" block in first line) Datatype: List l=[1,2,"a"] declared with [ ] brackets. l = []; l=[1,2]; l=[[]]

lists can be infinitely nested. (lists, tuples, dicts, sets can all be nested within each other)

["a"]*3 -> ["a","a","a"]; ["a","b"] + ["c","d"]

Other commands:

l.append(x) -> puts x to the end of the list

l.extend(c) -> appends all elements of containers

l.remove(x), l.insert(i,x), l.pop(i), l.sort(), l.count() ... Detour: containers and duck-typing Duck-typing: Methods and properties of objects determine the valid semantics (Not inheritance, like in java). "Anything that walks like a duck and swims like a duck and quacks like a duck is a duck".

Any class that contains the __contains__ function

is called a container.

It supports the x in object command. (Executed as object.__contains__(x)) Detour: mutable vs. immutable mutable objects can always be changed: l=[0,1] l[1]=c l[0]+=5

immutable objects cannot be changed after creation: t=(1,1) t[0]+=1

only immutables can be used as dictionary keys

Mutable: list, set, dict

Immutable: tuple, frozenset, bool, int, float, string

a=5 l=[a,5] a=3 l=? k=[l] l[1]=3 k=? Datatype: String s="abc" Datatype: Dict d={"a":1} A dictionary is a set of linked key:value pairs

Keys are unique and must be immutable

Dictionaries are very versatile: Hashing, counting, databases, connecting information.

Dictionaries are magic. Always use them! Datatype: Set st={1,2} Sets are an unordered collection of elements.

They support mathematical set operations

Members of a set must be hashable

frozensets are a immutable version of sets. datatypes Datatype: Tuple t=("a",1) t=(1,2), date=(year, month, day), address=('Arnimallee',22,14195,'Berlin')

tuples work similar to list, but they are immutable

tuples are often used implicitly:

a,b=b,a or return x,y

Use tuples if you don't need the list functions. Or if you need them as dict keys.

Some people prefer tuples for heterogeneous data

Defining classes

Python allows creating classes, but doesn't enforce it.

There are some notable special functions: __init__(self,args), __str__(self), __hash__(self) __cmp__(self), __iter__(self), next(self)

Classes can be nested. Or put inside a function. Or anywhere. pythonic stuff Module: argparse Module: os os provides system-specific functionality.

os functions work on different systems! Module: math basic mathematical functions:

math.pi, math.e, math.exp(), math. log()

math.factorial(), math.sqrt()

for more advanced maths:

numpy / scipy

plotting: matplotlib Module: itertools Advanced iteration functions

Includes useful, pythonic functions

import itertools as it

it.combinations(["a","b","c"],2)

-> ('a','b,) ('a','c') ('b','c')

it.permutations("abc",2)

for x,y in itertools.product(range(10),"abc"):

-> replaces nested loop over arguments Module: re Module: re Regular expressions - Theory modules Exception handling Reading arguments File I/O As easy as file=open("filename.ext","r")

"r"ead, "w"rite, "a"ppend

Textfiles - for line in file: to read file line by line.

file.close() or, more robust: with open('f','w') as f:

file.write("string") writes to file. Don't forget \n! basics That was: Python thanks for your attention. If you invoke a script: python script.py infile outfile 3

The arguments are found as a list: sys.argv

sys.argv[0] is the name of the script (script.py)

All other arguments, separated by whitespaces, follow as strings

So to use 3 as a number, you'd have to write int(sys.argv[3])

A more convenient way to handle arguments is argparse. More elegant way to parse arguments for scripts. Included in python 3.x. Examples List comprehension ... remember haskell?

map(f,list) zip(list1,list2) functools.reduct(f,list)

lambda functions f=lambda x,y:x*y

functools.reduce(lambda x,y:x+y, [1,2,3,4])

[x for x in range(2,1000) if not [y for y in range(2, int(x**0.5)+1) if x%y ==0]] 3.3 raw_input -> input ( )

Full transcriptParadigms: Object-oriented, imperative, functional

Scripting language (Interpreter, not a compiler)

Dynamic typing (example)

Indentation-based syntax Why python? Simple and powerful

Community-based, open source

Widespread use

Easily extendable

-> SQL, matlab, R support

Batteries included

Readable, compact syntax (Why not python? - slow.) Intermission - 3.3 vs 2.7 3.3 most recent version

3.3 backwards-incompatible (print ("x")) Still widespread use of 2.7

2.7 forwards-compatible (from __future__ import) We'll use 3.3 code compatible with 2.7 Functions Datatypes Control structures if

while

for for ... in ...: typical for python. Often more than one iteration possible: for i, x in enumerate(l): def starts a function

return returns variables

arguments follow in brackets

after function name

default arguments can be set using '='

use docstrings! (""" block in first line) Datatype: List l=[1,2,"a"] declared with [ ] brackets. l = []; l=[1,2]; l=[[]]

lists can be infinitely nested. (lists, tuples, dicts, sets can all be nested within each other)

["a"]*3 -> ["a","a","a"]; ["a","b"] + ["c","d"]

Other commands:

l.append(x) -> puts x to the end of the list

l.extend(c) -> appends all elements of containers

l.remove(x), l.insert(i,x), l.pop(i), l.sort(), l.count() ... Detour: containers and duck-typing Duck-typing: Methods and properties of objects determine the valid semantics (Not inheritance, like in java). "Anything that walks like a duck and swims like a duck and quacks like a duck is a duck".

Any class that contains the __contains__ function

is called a container.

It supports the x in object command. (Executed as object.__contains__(x)) Detour: mutable vs. immutable mutable objects can always be changed: l=[0,1] l[1]=c l[0]+=5

immutable objects cannot be changed after creation: t=(1,1) t[0]+=1

only immutables can be used as dictionary keys

Mutable: list, set, dict

Immutable: tuple, frozenset, bool, int, float, string

a=5 l=[a,5] a=3 l=? k=[l] l[1]=3 k=? Datatype: String s="abc" Datatype: Dict d={"a":1} A dictionary is a set of linked key:value pairs

Keys are unique and must be immutable

Dictionaries are very versatile: Hashing, counting, databases, connecting information.

Dictionaries are magic. Always use them! Datatype: Set st={1,2} Sets are an unordered collection of elements.

They support mathematical set operations

Members of a set must be hashable

frozensets are a immutable version of sets. datatypes Datatype: Tuple t=("a",1) t=(1,2), date=(year, month, day), address=('Arnimallee',22,14195,'Berlin')

tuples work similar to list, but they are immutable

tuples are often used implicitly:

a,b=b,a or return x,y

Use tuples if you don't need the list functions. Or if you need them as dict keys.

Some people prefer tuples for heterogeneous data

Defining classes

Python allows creating classes, but doesn't enforce it.

There are some notable special functions: __init__(self,args), __str__(self), __hash__(self) __cmp__(self), __iter__(self), next(self)

Classes can be nested. Or put inside a function. Or anywhere. pythonic stuff Module: argparse Module: os os provides system-specific functionality.

os functions work on different systems! Module: math basic mathematical functions:

math.pi, math.e, math.exp(), math. log()

math.factorial(), math.sqrt()

for more advanced maths:

numpy / scipy

plotting: matplotlib Module: itertools Advanced iteration functions

Includes useful, pythonic functions

import itertools as it

it.combinations(["a","b","c"],2)

-> ('a','b,) ('a','c') ('b','c')

it.permutations("abc",2)

for x,y in itertools.product(range(10),"abc"):

-> replaces nested loop over arguments Module: re Module: re Regular expressions - Theory modules Exception handling Reading arguments File I/O As easy as file=open("filename.ext","r")

"r"ead, "w"rite, "a"ppend

Textfiles - for line in file: to read file line by line.

file.close() or, more robust: with open('f','w') as f:

file.write("string") writes to file. Don't forget \n! basics That was: Python thanks for your attention. If you invoke a script: python script.py infile outfile 3

The arguments are found as a list: sys.argv

sys.argv[0] is the name of the script (script.py)

All other arguments, separated by whitespaces, follow as strings

So to use 3 as a number, you'd have to write int(sys.argv[3])

A more convenient way to handle arguments is argparse. More elegant way to parse arguments for scripts. Included in python 3.x. Examples List comprehension ... remember haskell?

map(f,list) zip(list1,list2) functools.reduct(f,list)

lambda functions f=lambda x,y:x*y

functools.reduce(lambda x,y:x+y, [1,2,3,4])

[x for x in range(2,1000) if not [y for y in range(2, int(x**0.5)+1) if x%y ==0]] 3.3 raw_input -> input ( )