Transcription of An Introduction to Python programming - fling.seas.upenn.edu
1 An Introduction to Python programmingKostas DaniilidisUPennAugust 27, 2015 Kostas Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 20151 / 26 Introduction Python is a simple, powerful and efficient interpreted language. Together with packages like NumPy, SciPy and Matplotlib, itprovides a nice environment for scientific works. The language that we will use for all the homeworks and mainly based on CIS 521 Python Tutorial: cis521/ slides from: casp/ Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 20152 / 26A Python code samplex = 34 - 23# A = "Hello"# Another = == == "Hello":x = x + 1y = y + " World"# String x = 34 - 23;String y = "Hello";double z = ;if ((z == ) || ( ("Hello"))) {x = x + 1;y = y + " World";} (x); (y);Kostas Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 20153 / 26 Basic Syntax Assignment uses = and comparison uses ==.
2 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 Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 20154 / 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 Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 20155 / 26 Dynamic Typing Java: statically typed Variables are declared to refer to objects of a given type.
3 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 Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 20156 / 26 Objects and Types Every entity is an object. Strongly typed: Every object has an associated type, which itcarries everywhere. Built-in object types: Number 10 String hello List [1, abc ,44] Tuple (4,5) Dictionary Files Missing: ArraysKostas Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 20157 / 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 Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 20158 / 26 Sequence Types 2 The sequence types share much of the same syntax andfunctionality.
4 # Tuplestu = (23, 'abc', , (2,3), 'def')# Listsli = ["abc", 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]# Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 20159 / 26 Operations on Listsli = [1, 11, 3, 4, 5] ('a')# [1, 11, 3, 4, 5, 'a'] (2, 'i')# [1, 11, 'i', 3, 4, 5, 'a']li = ['a', 'b', 'c', 'd'] ('b')# 1 - index of first ('b')# 2 - number of ('b')# ['a', 'c', 'd'] - remove first occurenceli = [5, 2, 6, 8] ()# reverse the list in ()# sort the list in placeKostas Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 201510 / 26 Dictionaries A mapping collection typed = {'user':'bozo', 'pswd':1234}.
5 D['user']# returns 'bozo'd['user'] = 'clown'd['user']# returns 'clown'Kostas Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 201511 / 26if, elif, elseif notdoneand(x > 1):doit()elifdoneand(x <= 1):dothis()else:dothat()Kostas Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 201512 / 26while, forwhile True:line = ReadLine()if len(line) == 0:breakforletterin'hello world':printletterforiin range(2,10,2):printiKostas Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 201513 / 26No 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 beused to distinguish between two function with the same name.
6 But operator overloading is possible using special methods onvarious Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 201514 / 26 Defining functionsdefget_final_answer(filename):" ""Documentation String"""line1line2returntotal_counterOu tsideTheFunction() 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 thefunction Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 201515 / 26 Creating a classclassrostercourse = "cis390"# called when an object is instantiateddef__init__(self,name,dept) = = dept# another member functiondefprint_details(self):print"Nam e: " + "Dept: " + = roster("john", "cis")# creating an ()# calling methods of an objectKostas Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 201516 / 26 Subclasses A class can extend the definition of another class Allows use (or extension) of methods and attributes already definedin the previous one.
7 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 (student): Python has no extends keyword like Java. Multiple inheritance is Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 201517 / 26 Redifining Methods Very similar to over-riding methods in Java To redefine a method of the parent class, include a new definitionusing 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 (self,a,b,c): The only time you ever explicitly pass self as an argument is whencalling a method of an (a,b,c):Kostas Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 201518 / 26initconstructor Very similar to Java.
8 Commonly, the ancestor sinitmethod is executed in additionto new commands. Must be done explicitly. You ll often see something like this in theinitmethod (self,x,y):Kostas Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 201519 / 26 Iterators in Pythonforein[1,2]:printe# 1# 2s = [1,2]it =iter(s) ()# ()# 2 Kostas Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 201520 / 26 Class with iterators in Python An iterator is any object with a next :"Iterator for looping over a sequence backwards"def__init__(self, data) = =len(data)defnext(self) == 0:raise = - [ ]def__iter__(self):returnselfKostas Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 201521 / 26 Class with iterators in Python 2forcharinReverse('spam')printchar# m# a# p# sKostas Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 201522 / 26 Useful Python packages NumPy Base N-dimensional array package SciPy Fundamental library for scientific computing Matplotlib Comprehensive 2D Plotting Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 201523 / 26 Numpy powerful N-dimensional array object.
9 Sophisticated functions. basic linear algebra functions. sophisticated random number Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 201524 / 26 Examples of NumPy operationsa = ([1.,2.,3.])define a vectorb = ([1.,2.,3.],[4.,5.,6.]) define a 2D (a,b)dot producta*belementwise (n)n by n identity (a)diagonal of (a)matrix (a)matrix (a,b)linear matrix equation solution(U,S,V) = (a)singular value (a)eigenvaluesKostas Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 201525 / 26 Scipy The SciPy library depends on NumPy. Gathers a variety of high level science and engineering discrete Fourier transform algorithmsIntegrate integration routinesInterpolate interpolation toolsLinalg linear algebra routinesOptimize optimization toolsSignal signal processing toolsSparse sparse matricesStats statistical functionsIo data input and outputSpecial definitions of many usual math functionsKostas Daniilidis (UPenn)An Introduction to Python programmingAugust 27, 201526 / 26