an introduction to python programming • python is a simple, powerful and efficient interpreted...

26
An Introduction to Python programming Kostas Daniilidis UPenn August 27, 2015 Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 1 / 26

Upload: tranmien

Post on 29-Jun-2018

287 views

Category:

Documents


0 download

TRANSCRIPT

An Introduction to Python programming

Kostas Daniilidis

UPenn

August 27, 2015

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 1 / 26

Introduction

• Python is a simple, powerful and efficient interpreted language.• Together with packages like NumPy, SciPy and Matplotlib, it

provides a nice environment for scientific works.• The language that we will use for all the homeworks and the

projects.

Slides mainly based on CIS 521 Python Tutorial:http://www.seas.upenn.edu/˜cis521/Lectures/python-review.pdf.

Some slides from: http://www.bioinfo.org.cn/˜casp/temp/python-workshop-slides.pdf

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 2 / 26

A python code sample

x = 34 - 23 # A comment.y = "Hello" # Another one.z = 3.45if z == 3.45 or y == "Hello":

x = x + 1y = y + " World" # String concat.

print xprint y

int x = 34 - 23;String y = "Hello";double z = 3.45;if ((z == 3.45) || (y.equals("Hello"))) {

x = x + 1;y = y + " World";

}System.out.println(x);System.out.println(y);

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 3 / 26

Basic Syntax

• Assignment uses = and comparison uses ==.• For numbers + - * / % are as expected.• Logical operators are words (and, or, not).• Simple printing can be done with (print).

• Identation matters to the meaning of the code.• Block structure indicated by identation.

• The first assignment to a variable creates it.• Variable types don’t need to be declared. Python figures them out.

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 4 / 26

Whitespace is meaningful

• Use a newline to end a line of code.• Two statements on the same line are separated with a semicolon ;• A long line can continue on next with \

• Block structure is indicated by identation.• The first line with less indentation is outside of a block.• The first line with more identation starts a nested block.

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 5 / 26

Dynamic Typing

• Java: statically typed• Variables are declared to refer to objects of a given type.• Methods use type signatures to enforce contracts.

• Python: dynamic typed• Variables come into existence when first assigned to.• A variable can refer to an object of any type.• All types are (almost) treated the same way.• Type errors are only caught in runtime.

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 6 / 26

Objects and Types

• Every entity is an object.• Strongly typed: Every object has an associated type, which it

carries everywhere.• Built-in object types:

• Number 10• String ”hello”• List [1,’abc’,44]• Tuple (4,5)• Dictionary• Files

• Missing: Arrays

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 7 / 26

Sequence Types 1

• Tuple• A simple immutable ordered sequence of items.• Immutable: a tuple cannot be modified once created• Items can be of mixed types including collection types

• Strings• Immutable• Conceptually very much like a tuple

• Lists• Mutable ordered sequence of items of mixed types.

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 8 / 26

Sequence Types 2

• The sequence types share much of the same syntax andfunctionality.

# Tuplestu = (23, 'abc', 4.56, (2,3), 'def')# Listsli = ["abc", 34, 4.34, 23]# Stringsst = "Hello World"; st = 'Hello World'# Accessing individual members of a sequence# Starting with 0tu[1] # 'abc'# Negative lookup: count from right, starting with -1tu[-3] # 4.56

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 9 / 26

Operations on Lists

li = [1, 11, 3, 4, 5]li.append('a') # [1, 11, 3, 4, 5, 'a']li.insert(2, 'i') # [1, 11, 'i', 3, 4, 5, 'a']

li = ['a', 'b', 'c', 'd']li.index('b') # 1 - index of first occurenceli.count('b') # 2 - number of occurencesli.remove('b') # ['a', 'c', 'd'] - remove first occurence

li = [5, 2, 6, 8]li.reverse() # reverse the list in placeli.sort() # sort the list in place

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 10 / 26

Dictionaries

• A mapping collection type

d = {'user':'bozo', 'pswd':1234};d['user'] # returns 'bozo'd['user'] = 'clown'd['user'] # returns 'clown'

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 11 / 26

if, elif, else

if not done and (x > 1):doit()

elif done and (x <= 1):dothis()

else:dothat()

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 12 / 26

while, for

while True:line = ReadLine()if len(line) == 0:

break

for letter in 'hello world':print letter

for i in range(2,10,2):print i

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 13 / 26

No function overloading

• There is no function overloading in Python.• Unlike Java, a Python function is specified by its name alone.• The number, order, names, or types of its arguments cannot be

used to distinguish between two function with the same name.

• But operator overloading is possible using special methods onvarious classes.

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 14 / 26

Defining functions

def get_final_answer(filename):"""Documentation String"""line1line2return total_counter

OutsideTheFunction()

• Function defining begins with def.• Function name, its arguments and colon follow.• No declaration of types of arguments or result.• return indicates the value to be sent back to the caller.• First line with less indentation is considered to be outside of the

function definition.

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 15 / 26

Creating a class

class rostercourse = "cis390"

# called when an object is instantiateddef __init__(self,name,dept):

self.student_name = nameself.student_dept = dept

# another member functiondef print_details(self):

print "Name: " + self.student_nameprint "Dept: " + self.student_dept

student1 = roster("john", "cis") # creating an instancestudent1.print_details() # calling methods of an object

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 16 / 26

Subclasses

• A class can extend the definition of another class• Allows use (or extension) of methods and attributes already defined

in the previous one.• New class: subclass. Original: parent, ancestor, superclass.

• To define a subclass, put the name of the superclass inparentheses after the subclass’ name on the first line of thedefinition.

class robotics_students(student):

• Python has no extends keyword like Java.• Multiple inheritance is supported.

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 17 / 26

Redifining Methods

• Very similar to over-riding methods in Java• To redefine a method of the parent class, include a new definition

using the same name in the subclass.• The old code won’t get executed.

• To execute the method in the parent class in addition to new codefor some method, explicitly call the parent’s version of the method.

parentClass.methodName(self,a,b,c):

• The only time you ever explicitly pass self as an argument is whencalling a method of an ancestor.

myOwnClass.methodName(a,b,c):

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 18 / 26

init constructor

• Very similar to Java.• Commonly, the ancestor’s init method is executed in addition

to new commands.• Must be done explicitly.• You’ll often see something like this in the init method of

subclasses:

parentClass.__init__(self,x,y):

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 19 / 26

Iterators in Python

for e in [1,2]:print e

# 1# 2

s = [1,2]it = iter(s)it.next()# 1it.next()# 2

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 20 / 26

Class with iterators in Python

• An iterator is any object with a next method.

class Reverse:"Iterator for looping over a sequence backwards"def __init__(self, data):

self.data = dataself.index = len(data)

def next(self):if self.index == 0:

raise StopIterationself.index =self.index - 1return self.data[self.index]

def __iter__(self):return self

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 21 / 26

Class with iterators in Python 2

for char in Reverse('spam')print char

# m# a# p# s

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 22 / 26

Useful Python packages

• NumPy• Base N-dimensional array package• http://wiki.scipy.org/Tentative_NumPy_Tutorial

• SciPy• Fundamental library for scientific computing• http://docs.scipy.org/doc/scipy/reference/tutorial/

• Matplotlib• Comprehensive 2D Plotting• http://matplotlib.org/

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 23 / 26

Numpy

• powerful N-dimensional array object.• sophisticated functions.• basic linear algebra functions.• sophisticated random number capabilities.

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 24 / 26

Examples of NumPy operations

a = np.array([1.,2.,3.]) define a vectorb = np.array([1.,2.,3.],[4.,5.,6.]) define a 2D matrixa.T matrix transposenp.dot(a,b) dot producta*b elementwise multiplicationnp.eye(n) n by n identity matrixnp.diag(a) diagonal of matrixnp.linalg.inv(a) matrix inversenp.linalg.pinv(a) matrix pseudoinversenp.linalg.solve(a,b) linear matrix equation solution(U,S,V) = np.linalg.svd(a) singular value decompositionnp.linalg.eig(a) eigenvalues

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 25 / 26

Scipy

• The SciPy library depends on NumPy.• Gathers a variety of high level science and engineering modules.

Fftpack discrete Fourier transform algorithmsIntegrate integration routines

Interpolate interpolation toolsLinalg linear algebra routines

Optimize optimization toolsSignal signal processing tools

Sparse sparse matricesStats statistical functions

Io data input and outputSpecial definitions of many usual math functions

Kostas Daniilidis (UPenn) An Introduction to Python programming August 27, 2015 26 / 26