introduction to python - knowledge technologies...

27
Introduction to Python Michael Krisper Thomas Wurmitzer March 22, 2014 Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 1 / 27

Upload: truonghanh

Post on 26-Apr-2018

264 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

Introduction to Python

Michael Krisper Thomas Wurmitzer

March 22, 2014

Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 1 / 27

Page 2: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

Schedule

TutoriumDates & DeadlinesSubmission SystemAssignment I: Example(Short) Python Introductionnetworkx, numpy & matplotlib

DisclaimerEdited but mostly based on Michael Krisper’s Python Introduction (withpermission). Thank you!

Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 2 / 27

Page 3: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

What is Python?

“Python is a dynamic, interpreted language. Source code does notdeclare the types of variables or parameters or methods. Thismakes the code short and flexible, and you lose the compile-timetype checking in the source code. Python tracks the types of allvalues at runtime and flags code that does not make sense as itruns.”1

Huge standard library and community.Huge list of 3rd party libraries2.If you want to know more about Python’s history checkout Guido’sBlog3 on that topic.

1https://developers.google.com/edu/python/introduction2https://github.com/vinta/awesome-python3http://python-history.blogspot.co.at

Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 3 / 27

Page 4: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

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 installthem 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 theWindows FAQ4.

4https://docs.python.org/2/faq/windows.htmlMichael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 4 / 27

Page 5: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

Writing Python using REAL $EDITOR

Figure 1: https://xkcd.com/378

Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 5 / 27

Page 6: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

Better than hoverboards!

Figure 2: https://xkcd.com/353/Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 6 / 27

Page 7: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

Writing Python: Hello World

% cat hello.pyprint 'Hello World'% python hello.py # Run code inside fileHello 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

Page 8: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

Writing Python: Hello World (Extended)

#!/usr/bin/env pythonimport sysimport math

def my_function(message):print messagereturn 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

Page 9: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

Writing Python: Calculations (interactive5)

% pythonPython 2.7.5 (default, Mar 9 2014, 22:15:05)

>>> 3+4 # output: 7>>> 5*3.7+1 # output: 19.5>>> 2**3-1 # output: 7>>> 5**70 # output: 847032947254...13916015625L>>> 3/2 # output: 1>>> 3/2.0 # output: 1.5>>> 3.0//4.0 # output: 0.0>>> 5*"a" # output: "aaaaa">>> 3+4 == 2**3-1 # output: True

Hint: from __future__ import divisionBefore: 3/2 -> 1, After: 3/2 -> 1.5

5https://docs.python.org/2/tutorial/interpreter.html#invoking-the-interpreterMichael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 9 / 27

Page 10: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

Writing Python: Variables & Assignments

>>> aTraceback (most recent call last):

File "<stdin>", line 1, in <module>NameError: name 'a' is not defined>>> a = 42 # integer>>> a42>>> 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

Page 11: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

Writing Python: Bool67

bool(None) # Falsebool(0) # Falsebool({}) # Falsebool([]) # Falsebool("") # False

bool(1) # Truebool([1,2,3,4]) # Truebool("Hello") # True# ...

6https://docs.python.org/2/library/functions.html#bool7https://docs.python.org/2/library/constants.html#False

Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 11 / 27

Page 12: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

Writing Python: Strings8

>>> s = 'Hello World'>>> s = "Hello World">>> s = """HelloWorld""" # Multiline

# Strings are Sequences>>> 'lie' in 'believe' # output: True>>> 'execute'.find('cute') # output: 3>>> 'foo' + 'bar' # output: foobar>>> '\n\nValar Dohaeris '.strip() # output: Valar Dohaeris>>> 'A;B;C\n;D'.split(';') # output: ['A', 'B', 'C\n', 'D']

>>> help(str)

8http://docs.python.org/2/library/stdtypes.html#string-methodsMichael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 12 / 27

Page 13: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

Writing Python: Conversion

>>> str(434) # '434'

>>> int('956') # 956>>> int('\n\n210 \r\n') # 210>>> int('5a')Traceback (most recent call last):

File "<stdin>", line 1, in <module>ValueError: invalid literal for int() with base 10: '5a'>>> int('5a', 16) # 90

>>> float('3.14') # 3.14

>>> type('434') # <type 'str'>>>> type(434) # <type 'int'>

Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 13 / 27

Page 14: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

Writing Python: Lists9

>>> a = [4, 8, 15] # list definition>>> a[0] # get first element>>> len(a) # length of the list>>> a[1:3] # get a slice by range>>> a[-1] # get last element>>> a.append(16) # append element>>> a += [55, 23, 42] # concat lists>>> a.remove(55) # remove an element>>> del a[5] # delete element on index>>> sorted(a) # sort the list

9https://docs.python.org/2/tutorial/datastructures.htmlMichael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 14 / 27

Page 15: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

Writing Python: Dictionary10

>>> 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")

10https://docs.python.org/2/tutorial/datastructures.htmlMichael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 15 / 27

Page 16: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

Writing Python: Built-in Datatypes (Excerpt)

int Integer 42Bool Boolean: True, False TrueLong Long Integer 10000000000000000L

Float Double 3.85Complex Complex Number (3.1+0.9j)

Str String “Jaqen H’ghar”List List / Array [1, 2, 5.5, "asdf", 0]Dict Dictionary {"a":"foo", "b":"bar"}Set Set Set([1, 2, 1, 3, True])

Tuple Tuple (1, 2, None, True, 4)

Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 16 / 27

Page 17: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

Writing Python: Built-in Functions11 (Excerpt)

len(...) Get length of a sequencemax(...)/min(...) Get max / min element of a sequenceopen(...) Open a file for read/writeprint Output to consoleinput(...) Read from consolerange(...)/xrange(...) Create a counter sequencesorted(...) Sort a sequencesum(...) Calculate the sum of a sequencetype(...) Get the type of a variable

Others: abs, dir, eval, format, hash, help, next, enumerate,ord, map, reduce, slice, unicode, zip, apply, ...

11https://docs.python.org/2/library/functions.html#built-in-funcsMichael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 17 / 27

Page 18: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

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 syssys.stdout.write("Who wrote the pink letter?")

12https://docs.python.org/2/library/functions.html#built-in-funcsMichael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 18 / 27

Page 19: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

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', 'sausage', 'spam']:print word

for i, word in enumerate(['ham', 'sausage', 'spam']):print i, word

while answer < 42:answer +=1

13https://docs.python.org/2/tutorial/controlflow.htmlMichael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 19 / 27

Page 20: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

Functions14

def say(string):print string

>>> say('Hello') # Output: Hello>>> say # Output: <function say at 0x102697938>>>> s = say>>> s('Hodor!') # Output: Hodor!

14https://docs.python.org/2/tutorial/controlflow.html#defining-functionsMichael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 20 / 27

Page 21: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

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()

15https://docs.python.org/2/tutorial/classes.htmlMichael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 21 / 27

Page 22: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

File I/O 16

fh = open('filename.txt', 'r')lines = fh.readlines()fh.close()

with open('filename.txt', 'w') as f:f.write("\n" % )

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")

16https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-filesMichael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 22 / 27

Page 23: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

(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 + aTraceback (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

17https://docs.python.org/2/tutorial/errors.htmlMichael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 23 / 27

Page 24: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

JSON18

The json module provides methods for easily reading and writing data fromand to files.

import json

json_string = '{'list': [1,2,3,4],'key': 'value', 'truth': 42 }'

content = json.loads(json_string)

print contents['truth'] # output: 42print contents['key'] # output: valueprint contents['list'] # output: [1,2,3,4]

18https://docs.python.org/2/library/json.htmlMichael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 24 / 27

Page 25: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

networkx19The networkx module/library provides functionality to create, analyze anddraw 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")

19http://networkx.github.io/documentation/latest/tutorial/tutorial.htmlMichael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 25 / 27

Page 26: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

Help & ResourcesUse help and dir in interactive mode.Library Documentation: networkx, numpy, matplotlibPython Language Reference

I https://docs.python.org/2/reference/index.htmlGoogle’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/pythonThe Hitchhiker’s Guide to Python!

I http://docs.python-guide.orgStackOverflow

I http://stackoverflow.com/questions/tagged/pythonReddit

I http://reddit.com/r/learnpythonMichael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 26 / 27

Page 27: Introduction to Python - Knowledge Technologies Institutekti.tugraz.at/staff/socialcomputing/courses/webscience/lectures/... · AssignmentI:Example (Short)PythonIntroduction networkx,numpy

Questions?

1 Ask now.2 Ask in the newsgroup tu-graz.lv.web-science.3 Send an e-mail:

I Dominik Mösslang, [email protected] Ingo Holzmann, [email protected] Emanuel Lacić, [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 thetu-graz.lv.web-science. If you have a particular, specific problem, youcan 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