Download Introduction to Python - KTI

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Introduction to Python
Michael Krisper
Thomas Wurmitzer
March 22, 2014
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
1 / 27
Schedule
Tutorium
Dates & Deadlines
Submission System
Assignment I: Example
(Short) Python Introduction
networkx, numpy & matplotlib
Disclaimer
Edited but mostly based on Michael Krisper’s Python Introduction (with
permission). Thank you!
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
2 / 27
What is Python?
“Python is a dynamic, interpreted language. Source code does not
declare the types of variables or parameters or methods. This
makes the code short and flexible, and you lose the compile-time
type checking in the source code. Python tracks the types of all
values at runtime and flags code that does not make sense as it
runs.”1
Huge standard library and community.
Huge list of 3rd party libraries2 .
If you want to know more about Python’s history checkout Guido’s
Blog3 on that topic.
1
https://developers.google.com/edu/python/introduction
https://github.com/vinta/awesome-python
3
http://python-history.blogspot.co.at
2
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
3 / 27
Installation
We use Python 2.7 - Python 3 is not supported (but may work)!
Linux: Most distributions already come with Python 2.7. If not install
them via your distributions packagemanager e.g. (pacman, apt, . . . )
OSX: All recent versions ship with Python 2.7 out of the box.
Windows: Windows Installer via python.org and check out the
Windows FAQ4 .
4
https://docs.python.org/2/faq/windows.html
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
4 / 27
Writing Python using REAL $EDITOR
Figure 1: https://xkcd.com/378
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
5 / 27
Better than hoverboards!
Figure 2: https://xkcd.com/353/
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
6 / 27
Writing Python: Hello World
% cat hello.py
print Hello World
% python hello.py # Run code inside file
Hello World
% python -c "print
Hello World " # Pass program as string.
% python # Interactive Mode
% ipython # ... on steroids
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
7 / 27
Writing Python: Hello World (Extended)
#!/usr/bin/env python
import sys
import math
def my_function(message):
print message
return math.e
# return constant from module
if __name__ == __main__ :
if len(sys.argv) < 2:
sys.exit(1)
result = my_function(sys.argv[1])
print math.ceil(result) # function in module
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
8 / 27
Writing Python: Calculations (interactive5 )
% python
Python 2.7.5 (default, Mar
9 2014, 22:15:05)
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
7
19.5
7
847032947254...13916015625L
1
1.5
0.0
"aaaaa"
True
3+4
5*3.7+1
2**3-1
5**70
3/2
3/2.0
3.0//4.0
5*"a"
3+4 == 2**3-1
#
#
#
#
#
#
#
#
#
output:
output:
output:
output:
output:
output:
output:
output:
output:
Hint: from __future__ import division
Before: 3/2 -> 1, After: 3/2 -> 1.5
5
https:
//docs.python.org/2/tutorial/interpreter.html#invoking-the-interpreter
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
9 / 27
Writing Python: Variables & Assignments
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name a is not defined
>>> a = 42
# integer
>>> a
42
>>> type(a)
# output: <type int >
>>> a += 1
# increase a by one
>>>
>>>
>>>
>>>
>>>
b = 1.78
# float
c = "Hello"
# string
d = [1,2,3,4] # list
e = (1,2,3)
# tuple
f, g = True, None
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
10 / 27
Writing Python: Bool67
bool(None)
bool(0)
bool({})
bool([])
bool("")
#
#
#
#
#
False
False
False
False
False
bool(1)
# True
bool([1,2,3,4]) # True
bool("Hello")
# True
# ...
6
7
https://docs.python.org/2/library/functions.html#bool
https://docs.python.org/2/library/constants.html#False
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
11 / 27
Writing Python: Strings8
>>> s = Hello World
>>> s = "Hello World"
>>> s = """
Hello
World
"""
# Multiline
# Strings are Sequences
>>> lie in believe
# output:
>>> execute .find( cute ) # output:
>>> foo + bar
# output:
>>> \n\nValar Dohaeris
.strip()
>>> A;B;C\n;D .split( ; ) # output:
True
3
foobar
# output: Valar Dohaeris
[ A , B , C\n , D ]
>>> help(str)
8
http://docs.python.org/2/library/stdtypes.html#string-methods
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
12 / 27
Writing Python: Conversion
>>> str(434)
#
>>> int( 956 )
>>> int( \n\n210
\r\n )
>>> int( 5a )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
>>> int( 5a , 16)
# 956
# 210
>>> float( 3.14 )
# 3.14
>>> type( 434 )
>>> type(434)
# <type
# <type
Michael Krisper, Thomas Wurmitzer
Introduction to Python
434
with base 10:
# 90
5a
str >
int >
March 22, 2014
13 / 27
Writing Python: Lists9
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
9
a = [4, 8, 15]
a[0]
len(a)
a[1:3]
a[-1]
a.append(16)
a += [55, 23, 42]
a.remove(55)
del a[5]
sorted(a)
#
#
#
#
#
#
#
#
#
#
list definition
get first element
length of the list
get a slice by range
get last element
append element
concat lists
remove an element
delete element on index
sort the list
https://docs.python.org/2/tutorial/datastructures.html
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
14 / 27
Writing Python: Dictionary10
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
10
d = { "key": "value", "key2": "value2" }
d["key"]
d.keys()
d.values()
d["key3"] = 45
"key" in d
len(d)
d.get("nokey", "default") # = "default"
d.setdefault ("nokey", "default")
https://docs.python.org/2/tutorial/datastructures.html
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
15 / 27
Writing Python: Built-in Datatypes (Excerpt)
int
Bool
Long
Float
Complex
Str
List
Dict
Set
Tuple
Integer
Boolean: True, False
Long Integer
Double
Complex Number
String
List / Array
Dictionary
Set
Tuple
Michael Krisper, Thomas Wurmitzer
42
True
10000000000000000L
3.85
(3.1+0.9j)
“Jaqen H’ghar”
[1, 2, 5.5, "asdf", 0]
{"a":"foo", "b":"bar"}
Set([1, 2, 1, 3, True])
(1, 2, None, True, 4)
Introduction to Python
March 22, 2014
16 / 27
Writing Python: Built-in Functions11 (Excerpt)
len(...)
max(...)/min(...)
open(...)
print
input(...)
range(...)/xrange(...)
sorted(...)
sum(...)
type(...)
Get length of a sequence
Get max / min element of a sequence
Open a file for read/write
Output to console
Read from console
Create a counter sequence
Sort a sequence
Calculate the sum of a sequence
Get the type of a variable
Others: abs, dir, eval, format, hash, help, next, enumerate,
ord, map, reduce, slice, unicode, zip, apply, ...
11
https://docs.python.org/2/library/functions.html#built-in-funcs
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
17 / 27
Writing Python: Built-in Functions12 (Excerpt)
print "Valar morghulis"
# with newline
print "Valar morghulis", # without newline
print "a = ", 1, " b = ", 2
print "a = %d b = %d" % (1,2)
print "{} of {}".format( mother ,
dragons )
import sys
sys.stdout.write("Who wrote the pink letter?")
12
https://docs.python.org/2/library/functions.html#built-in-funcs
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
18 / 27
Control Flow13
if points < 3 or bird is not word:
print "Erm, seriously?"
elif points < 10:
print "Seriously?"
else:
print "Good job!"
for word in [ ham ,
print word
sausage ,
spam ]:
for i, word in enumerate([ ham ,
print i, word
sausage ,
spam ]):
while answer < 42:
answer +=1
13
https://docs.python.org/2/tutorial/controlflow.html
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
19 / 27
Functions14
def say(string):
print string
>>>
>>>
>>>
>>>
say( Hello ) # Output: Hello
say
# Output: <function say at 0x102697938>
s = say
s( Hodor! ) # Output: Hodor!
14
https:
//docs.python.org/2/tutorial/controlflow.html#defining-functions
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
20 / 27
Classes15
class Human(object): # Inherits from object
def __init__(self, name): # Constructor
self.name = name
def speak(self):
print self.name, ": Valar Morghulis."
jh = Human("Jaqen H ghar");
jh.speak()
15
https://docs.python.org/2/tutorial/classes.html
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
21 / 27
File I/O
16
fh = open( filename.txt ,
lines = fh.readlines()
fh.close()
r )
with open( filename.txt ,
f.write("\n" % )
w ) as f:
with open( filename.txt , w ) as f:
f.write("%d + %d = %d\n" % (2,3,2+3))
f.write("Another line\n")
f.write("Another line\n")
16
https:
//docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
22 / 27
(Common) Exceptions17
>>> 2 + Hodor!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +:
int
and
str
>>> 2 + a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name a is not defined
>>> while Hodor print "Hodor!"
File "<stdin>", line 1
while Hodor print "Hodor!"
^
SyntaxError: invalid syntax
17
https://docs.python.org/2/tutorial/errors.html
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
23 / 27
JSON18
The json module provides methods for easily reading and writing data from
and to files.
import json
json_string =
{ list : [1,2,3,4],
key : value , truth : 42 }
content = json.loads(json_string)
print contents[ truth ] # output: 42
print contents[ key ]
# output: value
print contents[ list ] # output: [1,2,3,4]
18
https://docs.python.org/2/library/json.html
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
24 / 27
networkx19
The networkx module/library provides functionality to create, analyze and
draw complex networks.
import networkx as nx
G = nx.Graph()
G.add_node(1)
G.add_edge(1, 2)
G.add_edge(2, 3)
import matplotlib.pylab as plot
plot.figure()
nx.draw(G)
plot.savefig("graph.png")
19
http:
//networkx.github.io/documentation/latest/tutorial/tutorial.html
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
25 / 27
Help & Resources
Use help and dir in interactive mode.
Library Documentation: networkx, numpy, matplotlib
Python Language Reference
I
https://docs.python.org/2/reference/index.html
Google’s Python Class
I
https://developers.google.com/edu/python/
Think Python: How to Think Like a Computer Scientist
I
http://www.greenteapress.com/thinkpython/
Code Academy’s Python Track
I
http://www.codecademy.com/en/tracks/python
The Hitchhiker’s Guide to Python!
I
http://docs.python-guide.org
StackOverflow
I
http://stackoverflow.com/questions/tagged/python
Reddit
I
http://reddit.com/r/learnpython
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
26 / 27
Questions?
1
2
3
Ask now.
Ask in the newsgroup tu-graz.lv.web-science.
Send an e-mail:
I
I
I
Fiona Draxler, [email protected]
Thomas Wurmitzer, [email protected]
Please use [WSWT] or the course number 707.000 as a subject.
Please post general questions regarding the assignment tasks to the
tu-graz.lv.web-science. If you have a particular, specific problem, you
can contact us per e-mail as well. Answering delays might be longer,
though.
Michael Krisper, Thomas Wurmitzer
Introduction to Python
March 22, 2014
27 / 27