Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
MSDA Computer Programming Bridge Course Ozlem Garibay Chathika Gunaratne Outline • Concepts and hands on exercises • Sessions 1. 2. 3. 4. 5. 6. 7. 8. Introductions, installation, intro to python Data types, Functions and Methods Packages, Numpy Plotting with Matplotlib Pandas Review/Test Intro to Python • • • • • Interpreter, No compiling Portable, free No need to define vars Object Oriented and functional Good for rapid prototyping, Numeric and Scientific Programming, internet scripting, system programming, gaming, imaging, data mining, etc. • Operators: intuitive, overloaded – +: concatenate and plus – *: repeat and multiply Python Installation • What you need: – Python – Terminal – Text editor(textwrangler) • Installation – https://docs.google.com/document/d/1ICODI2rT4 IXay8TN1P5DjqxMyDKxv81o_s2aBkmrVw/edit?usp=sharing Python Shell • To run from the shell: – python – x=‘MSDA inaugural cohort’ – len(x); x[5] – y=‘ hi’; z=5 – x+y – x+y+z – x+y+str(z) • Multi=line commands: >>> for x in 'spam': print(x) Python Script • Python script – Indentation is important. – Hello.py import sys # import modules (functions) def main(): print ‘Hello there’, sys.argv[1] # to call the main() function if __name__==‘__main__’: main() – python hello.py arg1 arg2 arg3 … OR – ./hello.py arg1 arg2 arg3 … • python: to start a Python shell and ctrl-D to exit Example Python Help • To get help – help(function_name) • help(del) or ?del – Search online – dir(object) • Common functions: – – – – Print(a) Type(a) Len(a) Sorted(a) • Programs>Modules>Statements>Expressions>Objects Intro to Python • If control statement (if, elif, else) if withdraw >balance: return(false) else: balance-=withdraw return(true) • for loop >>> for c in 'spam': print(c.upper()) S P A M • while loop >>> x=4 >>> while x>0: print('spam!'*x) x-=1 spam!spam!spam!spam! spam!spam!spam! spam!spam! spam! Data Types • Dynamically and strongly typed • Single Value: – Numbers • Int: integer • Float : real number – Bool: true or false – Str: string • Multiple Value: – – – – – List [a, b, c] Dictionary Tuple File Set Numbers • >>>a=5 • >>>a*3 15 • >>>a**2 25 • >>>Import math • >>>math.pi 3.1415… • >>>math.sqrt(49) 7 • >>>import random • >>>random.random() # generate a random number • >>>random.choice([2,1,7,9,5]) #randomly select from the list Strings • >>>s=‘spam’ • >>>s[0] ‘s‘ • >>>len(s) 4 • >>>S.replace(‘pa’, ’xyz’) ‘sxyzm’ • >>>s ‘spam’ • >>>s.isalpha() True • >>>s.upper() ‘SPAM’ • >>>s=‘aaa,bbb,ccc,ddd’ • >>>s.split(‘,’) [‘aaa’, ‘bbb’, ‘ccc’, ‘ddd’] • ‘%s pizza and %s please’ %(‘cheese’, ‘coke’) Lists • Indexing: Zero indexed – Fam=[“mary”, 52, “john”, 55, “jeff”, 15, “sally”, 10] Index Negative index 0 1 2 3 4 5 6 7 -8 -7 -6 -5 -4 -3 -2 -1 Fam[5]=15 Fam[2]=“john” Fam[-1]=10 Fam[-6]=“john” • Slicing: – Fam=[“mary”, 52, “john”, 55, “jeff”, 15, “sally”, 10] Index 0 1 2 Fam[3:6]=[55, ”jeff”, 15] 3 4 5 [start: end] Inclusive Exclusive Fam[:6]=[“mary”, 52, “john”, 55, ”jeff”, 15] Fam[3:]=[55, ”jeff”, 15, “sally”, 10] 6 7 Lists • Fam=[52, 55, 15, 10] – – – – – – – – – – – – – >>> del Fam[1] >>> Fam [52, 15, 10] >>> Fam.pop(1) 55 >>> Fam [52, 15, 10] >>> Fam.sort() >>> Fam [10, 15, 52] >>> Fam.reverse() >>> Fam [52, 15, 10] List - Nesting • In: house=[['hallway', 11.25], ['kitchen', 18.0], ['living room', 20.0], ['bedroom', 10.75], ['bathroom', 9.5]] • In: house[-1][1:] • Out: [9.5] • >>>col1=[i[0] for i in house] Manipulating List • In: x=['a', 'b', 'c'] – Changing • In: x[0]=‘t’ • x=[‘t', 'b', 'c'] – Adding • • • • In: x=x + [‘z‘] [‘t', 'b', 'c’, ‘z’] In: x.append(‘r’) [‘t', 'b', 'c’, ‘z’, ’r’] • y=x – y=[‘b', ‘c', ‘z'] – x and y point to the same list. x [‘b', ‘c', ‘z'] y Copying List • y=list(x) or y=x[:] • Two copies of the list, x and y points to two separate lists • x[0]=‘k’ x [‘b', ‘c', ‘z'] y [‘b', ‘c', ‘z'] • x=[‘k', ‘c', ‘z'] • y=[‘b', ‘c', ‘z'] Example • • • • • • >>> L=range(3, 17, 3) >>> L [3, 6, 9, 12, 15] Filter out the odd numbers >>> [L[i] for i in range(5) if L[i] %2==0] [6, 12] Example • • • • • • • • • • Create a 4 x 4 matrix and collect a diagonal from the matrix. >>> m=range(6,10); l=range(16,20); k=range(26,30) >>> m [6, 7, 8, 9] >>> z=[l,m,k,n] >>> z [[16, 17, 18, 19], [6, 7, 8, 9], [26, 27, 28, 29], [7, 8, 9, 10]] >>> d=[z[i][i] for i in [3,2,1,0]] >>> d [10, 28, 7, 16] Dictionaries • Mapping – – – – – – – – – – – – – Stores objects by key instead of relative position. >>> D1={} >>> D1['name']='Bob' >>> D1['age']=40 >>> D1['gender']='M' >>> D1 {'gender': 'M', 'age': 40, 'name': 'Bob'} >>> D2=dict(name='Lisa', age=25, gender='F') >>> D2 {'gender': 'F', 'age': 25, 'name': 'Lisa'} >>> D3=dict(zip(['name','age','gender'],['Sally',63,'F'])) >>> D3 {'gender': 'F', 'age': 63, 'name': 'Sally'} Dictionaries • >>> record={'name':{'first':'bob', 'last': 'smith'}, 'age': 40, 'job':['dev', 'mgr']} • >>> record • {'job': ['dev', 'mgr'], 'age': 40, 'name': {'last': 'smith', 'first': 'bob'}} • >>> record['name'] • {'last': 'smith', 'first': 'bob'} • >>> record['name']['last'] • 'smith' • >>> record['job'][-1] • 'mgr' Tuples • • • • Sequences similar to list Immutable similar to string Supports arbirary types and nesting Allows to preserve integrity • T=(1,2,3,4) • • len(T) Out[2]: 4 • • T+(5,6) Out[3]: (1, 2, 3, 4, 5, 6) • • T Out[4]: (1, 2, 3, 4) • • T.index(4) Out[6]: 3 • • T.count(4) Out[7]: 1 • • T[0] Out[5]: 1 • • T[0]=2 TypeError: 'tuple' object does not support item assignment • • T.append(2) AttributeError: 'tuple' object has no attribute 'append' Files • Read/write • Text,audio,excel,email • f=open('firstfile.txt', 'w') • • • • • • • • • ls 08/04/2016 11:01 AM <DIR> . 08/04/2016 11:01 AM <DIR> .. 08/04/2016 10:48 AM 283,147 bridge_august1.pptx 08/04/2016 11:01 AM 0 firstfile.txt 08/02/2016 11:49 AM <DIR> google-python-exercises 08/01/2016 01:17 PM <DIR> overview 5 File(s) 502,233 bytes 4 Dir(s) 17,767,260,160 bytes free • f.write('first file\n write example') Files • f.close() • • filecontect=f.read() ValueError: I/O operation on closed file • f=open('firstfile.txt') • filecontext=f.read() • • filecontext Out[22]: 'first file\n write example' • • print(filecontext) first file write example • • filecontext.split() Out[24]: ['first', 'file', 'write', 'example'] Sets • Unordered collections of unique and immutable objects. • Neither sequence nor mapping • • • • • • • • • • • • • • • • • • • • • • >>> X=set('spam') >>> Y={'h','a','m'} >>> X,Y (set(['a', 'p', 's', 'm']), set(['a', 'h', 'm'])) >>> X&Y # intersection set(['a', 'm']) >>> X|Y ##union set(['a', 'p', 's', 'h', 'm']) >>> X-Y set(['p', 's']) >>> X>Y #superset? False >>> l=[1,2,1,3,1] #filter out duplicate >>> l=list(set(l)) >>> l [1, 2, 3] >>> set('spam')-set('ham') # finding out differences in collections set(['p', 's']) >>> set('spam')==set('pams') #order neutral equality True >>> 'p' in set('spam') True Numerical Operators • • • • • • • • • • • • • • Operators: +,-,*,/,>>,**,& etc. Functions: Pow, abs,round,int,float etc. Modules: random, math etc. >>>x=40; x/3 13 >>> x//3 13 >>> float(x)/3 13.333333333333334 >>> type(x) <type 'int'> >>> x=float(x) >>> type(x) <type 'float'> Numerical Operators • • • • • • • • • • • • • • • • • >>> x/3 13.333333333333334 >>> z=7 >>> x+y*z 71.5 >>> y 4.5 >>> (x+y)*z 311.5 >>> 1<2 True >>> x>z>y True >>> z<x>y True >>> x!=y<z True Functions • Piece of code to do a particular task. – output = function_name(input1[,input2, …]) – max(), round(), str(), int(), type(), bool(), float(), sorted() – Ex: a=[20.0, 18.0, 11.25, 10.75, 9.5] max(a) -> 20.0 – To get help • help(function_name) – help(max) or ?max Methods • Methods: Functions called on objects • In python, eveything=object • Object have methods associated with them depending on type. – Ex: fam=[“mary”, 52, “john”, 55, “jeff”, 15, “sally”, 10] Index 0 1 2 3 4 5 6 7 In: fam.index(“john”) # call method index() on fam list object Out: 2 In: fam.append(“jason”) # call method append() to add “jason” in the list In: fam Out: mary”, 52, “john”, 55, “jeff”, 15, “sally”, 10, “jason”] Example Example Example Exercise List2 Example - Wordcount Example - Wordcount Example - Wordcount