Class Note for EECS 448 with Professor Niehaus at KU 3
Class Note for EECS 448 with Professor Niehaus at KU 3
Popular in Course
Popular in Department
This 9 page Class Notes was uploaded by an elite notetaker on Friday February 6, 2015. The Class Notes belongs to a course at Kansas taught by a professor in Fall. Since its upload, it has received 27 views.
Reviews for Class Note for EECS 448 with Professor Niehaus at KU 3
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 02/06/15
Introduction to Python EECS 448 Dr Douglas Niehaus EECS 448 1 Dr Douglas Niehaus 2009 Overview Python was explicitly designed for Object Orientation Extension using CC CC implementations of specific capabilities are made available as Python commands Support for Modules which are essentially libraries providing support for specific activities Huge number of Python modules for a wide range of tasks Data base interface multithreading sockets and distributed computing numerical methods NumPy data display Matplotlib graph theory compression image mkaIlr ipulation bioinformatics WWWCGI EECS 448 3 Dr Douglas Niehaus 2009 Overview Python is an interpreted scripting language which is easy to use and represents a class of languages suitable for a range of software projects Small simple tools Oneoff scripts helping with daytoday SWE GUI based front ends for configuration files command line tools and system services Large scale implementations have also been done Python is comparable to Perl Ruby Bash in many ways Java in some other ways Pyton is byte compiled and runs on a VM much as Perl and Java EECS 448 2 Dr Douglas Niehaus 2009 Overview As a scripting language Python is dynamically typed and can be used much more freely than a statically typed language such as C Amazingly powerful code can be written in an amazingly few lines It can be scary and even a bit hard to figure out why is is all working correctly Python is has been used by Google for many years for many of its internal implementations Python creator Guido van Rossum employed in part to keep developing Python Red Hat uses Python for Kickstart Linux Setup Django WWW framework developed at Lawrence Journal World EECS 448 4 Dr Douglas Niehaus 2009 Overview Python Interpreter Reasonably efficient although scripting languages are generally somewhat slower than compiled languages Psyco and other Python accelerators PythontoC compilers have been tried Python is used for large scale highperformance Scientific computing CCFortran numbercrunching cores NumPy widely used CrossPlatform LinuxUnix Windows OS X GTK and WXWidgets crossplatform as well EECS 44B 5 Dr Douglas Niehaus 2009 Online Resources Python interpreter can be invoked from the command line and some people use it as their shell Bashgt pythonquot gives the Python prompt gtgtgtquot Exit Python interpreter using CTLD or gtgtgt import sys syseXitquot This imports the sys module and then calls the exit routine within the sys module name space Importing a module brings in a new set of capabilities Elements of a module are referred to suing the modulenameelementquot naming scheme when imported in the basic way Other forms available google Python importquot EECS 448 Dr Douglas Niehaus 2009 Fundamentals Google on obvious search strings is amazingly although not universally effective wwwpythonorg Home page of Python Language Documentation section contains links to tutorials module documentation and library references Dive into Python Online book which is generally a good introduction httpwwwdiveintopythonorgtocindexhtml EECS 44B 7 Dr Douglas Niehaus 2009 Indentation and Block Structure Comments and Printing Variables and Assignment Expressions Numbers Strings Lists and Tuples Dictionaries BuiltIn Functions None Value Scripts Functions EECS 44B 8 Dr Douglas Niehaus 2009 Indentation and Block Structure Comments and Printing Unusual and unnerving fact White Space matters in Python Indent with TABS Surprisingly easy to deal with Can make copypastequot a bit tedious Much less of an issue than your first reaction might indicate Eric Raymond Cathedral and the Bazaar avoided Python for a year because of this n 9 r 5 for i in range10 print d dquot i nir EECS 44B 9 Dr Douglas Niehaus 2009 Variables and Assignment Comments are started with pound sign All characters after are ignored Printing lnvokes the print method of the variable type gtgtgti 7 print nquot gtgtgtfred this is a stringquot print fred Format string follows CC printf model print formatstringquot o tuple of values gtgtgtprint d d is the value s is the stringn 35 foo fred Google printf formatquot python print formatquot od decimal of floating point 3 string 39 ooh heX n newline t tab EECS 44B 10 Dr Douglas Niehaus 2009 Expressions Variables are not declared or explicitly typed Variables are created by assigning into them Quick and flexible Also possibly scary i5 typei i foo typei i 137 typei Single variable name changes type as assigned different type values type is a Python builtin function Assignment is used to create class member variables generally in the initquot constructor method Boolean TrueFalse Integers Floating Point EECS 44B 11 Dr Douglas Niehaus 2009 Expressions generally just workquot following obvious conventions from your previous experience Type coercion follows CC rules Precedence as in CC Fully parenthesize is a good approach Plus operator also overloaded for strings and some other types concatenates strings Interpreter command line easy to us to test a given scenario EECS 44B 12 Dr Douglas Niehaus 2009 Numbers Strings Integers floats long hex complex 5 J12345678L fred0x234 Jane 20 John 1567e14 Conversion routines Number gt string print stringform print oxquot o hexnum String gt number Conversion routines built in for many types including all numbertypes intquot345quot Jfloat 2345quot khex 0x967quot Again experimentation is easy and printin the result or typeresult almost always revealst e truth EECS 44B 13 Dr Douglas Niehaus 2009 Lists and Tuples ASCII and Unicode Fred This is the ASCII stringquot John uquotThis is the Unicode stringquot Unicode mostly significant for complex more than 8 bit character sets Kanji Arabic Chinese etc Don t worry about Unicode unless some input requires it Strings are also sequence types like lists and tuples Wide range of methods available for operating on strings in various ways strip find index split join replace translate EECS 44B 14 Dr Douglas Niehaus 2009 Dictionaries Very similar Both are sequences as are strings Lists are mutable changeable tuples are not List sequence of arbitrary elements 1 2345 fredquot 3 30quotfooquot istquotquotwithinquotquotistquot Tuples 1 2345 fredquot 3 30quotfooquot Slicing L 1 2345 print L3 L03 L4L2 List Methods Append count index insert sort reverse dirL EECS 44B 15 Dr Douglas Niehaus 2009 Python dictionaries a associate key value pairs Hash tables behind the scenes Also serve as a front end for MySQL or other DB Curly braces denote a dictionary dict keystringquot 32 14 string valquot Key values must be immutable Integers and tuples Strings are among the most common Immutability is subtle but changing strings creates a new string Assignment dict new key aquot 3 b 5 EECS 448 Dr Douglas Niehaus 2009 Dictionaries Useful for many purposes Straightforward data collections C structure strct FNamequot John equivalents Namesl392i 8mithquot I I I gequot Egd name 398 the fndict quot01quot f1 quot02quot f2 quot03quot is D M Dict of functions Roughly equivalent to C switch statement with each case implemented as a function case classifystate struct fndictcasestate struct EECS 44B 17 Dr Douglas Niehaus 2009 BuiltIn Functions Some internal and introspective functions Compile eval exec compile a string containing python code that can be used with exec or eval dirobject return a directory listing of object attribites useful for learning about classes defined by modules Math functions Exceptions Numeric Conversions Scan Documentation EECS 44B 19 Dr Douglas Niehaus 2009 Dictionaries dhaskey LNamequot checks if dictionary d has an entry with key value Lname fhaskey14 check iff has an entry with key 14 keylist dkeys keylist set to all keys in d Delete an entry del dict keyvaluequot value fredget13 notfoundquot Fetch the value associated with key 13 in fred if present or return string notfoundquot Equivalent to if fredhaskey13 value fred13 else value hamfoundquot EECS 448 Dr Douglas Niehaus 2009 None Special Value None is a special value denoting that a variable has no content no type it has never been assigned into Can be useful when testing to see if a parameter has been specified or ignored EECS 44B 20 Dr Douglas Niehaus 2009 Scripts Everything can be in a file Assume fredpy bashgt chmod X fredpyquot gives execute permissions bashgtfredpyquot is then possible Inside fredpy on the first line lusrbinenv python print I am the script fredpyquot Can also do bashgtpython fredpyquot First line interpreter specification also works for other languages including Bash lusrbinenv bash EECS 44B 21 Dr Douglas Niehaus 2009 Func ons Functions can return any value including lists tuples dictionaries function references etc def returntuple 0 A 1 8 123 C string value return A B C trv returntuple John Joe Sue trv frist second third returntuple EECS 44B 23 Dr Douglas Niehaus 2009 Func ons Simple definition syntax note the colon def foo p1 p2 Printf p1 p1 and p2 p2 nquot Can be called with any types given as parameters Can return any type and even more than one value def returnmultiple 0 A 1 8 123 C string value Return A B C John Joe Sue returnmultiple Keyword and Default parameters are useful EECS 44B 22 Dr Douglas Niehaus 2009 Conditionals lfthenelse is basic conditional statement Conditional statements have all basic operators ltgtltgt not and or True and False are also values No then keyword colon denotes end of condition Clauses are indented elif keyword forchaining 39faibi I print a less than b Exceptions can happen em b lt a Values not comparable print Ibis lessthan 8quot else False None All evaluate as FALSE EECS 448 print a and b are equal Dr Douglas Niehaus 2009 File lO Iteration and Looping 39 Ogentbum39in returns a le inf openfootxtn rangex creates as list of integers from O to x1 o Jec 39 outf openquotfredtxtquotquotwquot line infreadline while line print linesquot line outfwriteline line infreadline infclose Open for read by default FeadlineO method reads one Ine readlines reads all into one big string variable read and write methods operate on sets of characters dirinf gives a list of methods print can take a file object modifier import sys sysstdoutwrite Helloquot outfclose EECS 44B 25 Dr Douglas Niehaus 2009 Iteration and Looping print gtgtoutf Extra Line nquot range6x list from 6 through x1 Also takes a step argument for loop iterates through a list of items fori in range7 print i is i Variable i assigned values 0 6 Items can be any listtupleset or object supporting iteration for k in dictkeys for char in abcdefg for line in open footxtquot EECS 44B 26 Dr Douglas Niehaus 2009 Iteration and Looping While loop has obvious syntax testing condition while a lt b print a is still less than bnquot List comprehension newist exprx for X in odist exprx is an expression in terms of x x iterates through odist and each element of newist has the value exprx for each x in odist Zip zips1s2sk take k sequences returning a new sequence where each element is alist of the nth element of each of the k sequences Map mapfuncs return a new sequence whose values are the result of funcx for each element x in s Can take n sequences for n args to func EECS 44B 27 Dr Douglas Niehaus 2009 Reduce reducefuncs can use func to accumulate over elements of sequence s def sumxy return xy a 1234 b reducesuma 1234 Filter filterfunc s func returns a sequence containing elements of s for which funcs returns True EECS 44B 28 Dr Douglas Niehaus 2009 Classes Basic support for class definition Methods and variables public Double beginning underscore can be used for private methods Python interpreter mangles names further Some standard methods begin and end with double underscores Constructor init Destructor de All methods take self as a first argument Reference to the class instance object EECS 44B 29 Dr Douglas Niehaus 2009 Classes Remember that the class statement does not create instances of the class X C call to constructor does that Inheritance works in the obvious ways class CA defines class C as inheriting from class A Operator overloading repr method returns a string that can be evaluated as Python to reproduce the object strlmethod returns a string used when using a class Instance as an argument of print add and sub are and operators EECS 44B 31 Dr Douglas Niehaus 2009 Classes Constructor used to Vusrbinenv Python initialize instances class 01 def initigselfdnitib Should create all se rfa1 class variables by 5939 quot th assigning default def m1sef N values print M1 n selfX gives access to defrgt z ei 39g member variables and def m3 self medthOds from Class return slgfb selfim2 CO e Calls have one lessquot parameter than the definition of methods if Tn mn3e 4 re fredm1 print quotresult fredm3 maini39 Uncomment for exception print quotim2 returns fred7m2 O EECS 44B 3 Dr Douglas Niehaus 2009 Modules Wide range of modules supporting a wide range of functionality are available Brought into a Python application using any of several forms of the import statement Any Python file can be imported as a module Create foopy import foo Places where interpreter looks for foopy is defined by syspath gtgtgtimport sys print syspathquot Current directory is at the frint of list Add elements syspathappendnewdirpath newddirpath should be an absolute path EECS 44B 32 Dr Douglas Niehaus 2009 Modules PYGTK Module Test of name against mainquot useful to encapsulate testing and demo code for module Can define functions within True clause of test Paths of ZIP files can also be added to path syspathappendpathtozip ZIP files can contain several module files All in a flat directory structure Multilevel directory structure requires adding directory path components within zip file syspathappend homeniehausfoofredziputilquot EECS 44B 33 Dr Douglas Niehaus 2009 GTK is now a standard and popular widget set of Linux and also available on windows Originally developed for GIMP application but now used by GNOME desktop KDE used the QT widget set wxwidgets aslo exist and older TK widgets are still aroun Usable from many languages C is default PyGTK is a Python wrapping of GTK Fairly easy to learn Good online resources Read Python source of examples EECS 44B 34 Dr Douglas Niehaus 2009
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'