ee 355 unit 17
play

EE 355 Unit 17 Python Mark Redekopp 2 Credits Many of the - PowerPoint PPT Presentation

1 EE 355 Unit 17 Python Mark Redekopp 2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 3 Python in Context Interpreted, not compiled like C++


  1. 1 EE 355 Unit 17 Python Mark Redekopp

  2. 2 Credits • Many of the examples below are taken from the online Python tutorial at: – http://docs.python.org/tutorial/introduction.html

  3. 3 Python in Context • Interpreted, not compiled like C++ – Slower – Better protection (no seg. faults) – Memory allocation handled automatically • Mainly for scripting (not for production) – Major competitor is Perl • Object-oriented – Supports encapsulation, inheritance, polymorphism – Everything is public

  4. 4 Interactive vs. Scripts • Can invoke python and work interactively – % python >>> print "Hello World" // command prompt Ctrl-D (Linux/Mac) [Ctrl-Z Windows] at the prompt will exit. • Can write code into a text file and execute that file as print "Hello world" a script – % python myscript.py myscript.py • Can turn on executable bit and execute directly – % chmod u+x myscript.py – % ./myscript.py #! /usr/bin/env python print "Hello world" myscript.py

  5. 5 Types >>> 2 + 1 • Types 3 >>> 2.5 + 1.0 – Bool 3.5 >>> 2+4j + 3-2j – Integers (5+2j) >>> "Hello world" – Floats 'Hello world' >>> 5 == 6 – Complex False – Strings • Dynamically typed >>> x = 3 >>> x = "Hi" – No need to "type" a variable >>> x = 5.0 + 2.5 – Python figures it out based on what it is assigned myscript.py – Can change when re-assigned

  6. 6 Strings • Enclosed in either double >>> 'spam eggs' 'spam eggs' or single quotes >>> 'doesn\'t' – The unused quote variant "doesn't" >>> "doesn't" can be used within the "doesn't" string >>>'"Yes," he said.' '"Yes," he said.' • Can concatenate using >>> "Con" + "cat" + "enate" the ‘+’ operator 'Concatenate' >>> i = 5 • Can convert other types >>> j = 2.75 >>> "i is " + str(i) + " & j is" + str(j) 'i is 5 & j is 2.75' to string via the str(x) method

  7. 7 Simple Console I/O • Print to display using ‘print’ >>> print 'A new line will' >>> print 'be printed' – If ended with comma, no newline will A new line will be printed be output >>> print 'A new line will', – Otherwise, will always end with >>> print ' not be printed' A new line will not be printed newline • >>> response = raw_input("Enter text: ") raw_input allows a prompt to be Enter text: I am here displayed and whatever text the user >>> print response = raw_input("Enter a num: ") responds with will be returned as a Enter a num: 6 6 string >>> x = int(response) • Use int( string_var ) to convert to >>> response = raw_input("Enter a float: ") integer value Enter a float: 6.25 • Use float( string_var ) to convert to >>> x = float(response) float/double value

  8. 8 Variables & Memory Allocation Object/Memory Namespace Space • All variables can be >>> x = 6 + 2 x 8 thought of as references >>> y = "Hi" (i.e. C++ style >>> z = 5.75 y “Hi” references) • RHS expressions z 5.75 create/allocate memory for resulting object Object/Memory Namespace • LHS is a variable name Space Memory space associated with that reclaimed 8 >>> y = "Hello" x object >>> x = z • Assignment changes “Hi” y that allocation z 5.75 • When no variable name is associated with an “Hello” object, that object is Equiv. C++ deallocated int &x = *(new int(8)) string &y = *(new string("Hi"))

  9. 9 Tuples • Like an array but can >>> x = ('Hi', 5, 6.5) store heterogeneous >>> print x[1] 5 types of objects >>> y = x[2] + 1.25 • Comma separated values 7.75 >>> x[2] = 9.5 between parentheses Traceback (most recent call last): • Immutable File “< stdin >”, line 1, in <module> TypeError : ‘ tuple ’ object does not support item – After initial creation, assigned cannot be changed

  10. 10 Lists >>> x = ['Hi', 5, 6.5] • Like tuples but individual >>> print x[1] elements can be reassigned 5 • Comma separated values >>> y = x[2] + 1.25 7.75 between square brackets >>> x[2] = 9.5 • Similar to vectors >>> x – Efficient at appending and ['Hi', 5, 9.5] popping back of the list >>> x.append(11) ['Hi', 5, 9.5, 11] • Can contain heterogeneous >>> y = x.pop() >>> x types of objects ['Hi', 5, 9.5] • Basic functions: >>> y = x.pop(1) >>> x – append(value) ['Hi', 9.5] >>> len(x) – pop(loc) 2 – len

  11. 11 Variables & Memory Allocation Object/Memory Namespace Space • Assignment of a variable >>> x = [4,5,9] x [4,5,9] referencing a mutable, >>> y = x composite object (lists, y etc.) to another Object/Memory Namespace variable is essentially a Space >>> x[1] = 7 shallow copy (two x [4,7,9] >>> print y[1] reference of the same 7 data) y • Call "copy" constructor to make a deep copy if Object/Memory Namespace desired Space >>> x = [4,5,9] x [4,5,9] >>> y = list(x) >>> a = 5 y [4,5,9] >>> b = a >>> b = 7 a 5 >>> print a 5 b 7

  12. 12 Variable/Reference Gotcha Object/Memory Namespace Space • Consider the following >>> x = [4,5,9] x [4,5,9] code >>> y = x • What will the length of y y be in the 2 nd code box Object/Memory Namespace Space >>> x = [] x [ ] >>> print len(y) y You think this is what you have… Object/Memory Namespace Space >>> x = [] >>> x = [] x [ ] >>> print len(y) >>> print len(y) 3 y [4,5,9] …when, in fact, you have this

  13. 13 Handy String Methods • Can be subscripted >>> word = 'HelpA' >>> word [4] – No character 'A' >>> word[0:2] type…everything is a string 'He' >>> word[2:4] • Can be sliced using ‘:’ 'lp' >>> word[:2] – [Start:End] 'He' – Note end is non-inclusive >>> word[3:] 'pA' • Len() function >>> len(word) 5 • Immutable type >>> word[0] = 'y' – To change, just create a new Traceback (most recent call last): File “< stdin >”, line 1, in ? string TypeError: object does not support item assignment >>> word = 'y' + word[1:]

  14. 14 Handy String Methods 2 • find(), rfind() >>> "HelpA".find('elp') 1 – Finds occurrence of substring and >>> "yoyo".rfind("yo") return index of first character or -1 if 2 not found >>> "yoyo".find("ooo") • in -1 >>> "yo" in "yoyo" – Returns boolean if substring occurs True in string >>> "yoyo".replace("yo","tu") • replace() 'tutu' • >>> "!$%".isalphnum() isalpha(), isnum(), isalnum(), False islower(), isupper(), isspace() >>> "A 123"[2:].isnum() – True return boolean results >>> x = "The cow jumped over the moon" • split( delim ) >>> x.split() – >>> x returns a list of the string split into ['The','cow','jumped','over','the','moon'] multiple strings at occurrences of >>> x[2] delim 'jumped' – delim defaults to space

  15. 15 Handy List Methods • Can be sliced using ‘:’ >>> x = [4, 2, 7, 9] >>> x[3] – [Start:End) 9 – Note end is non-inclusive >>> x[0:2] [4,2] • len() function >>> x[2:] [7, 9] • item in list >>> 2 in x – Return true if item occurs in list True • sort() >>> x.sort() – Sorts the list in ascending order [2, 4, 7, 9] – Works in place >>> x.append(4) [9, 7, 4, 2, 4] • reverse() >>> x.count(4) • min(), max(), sum() 2 • count(item) – Counts how many times item occurs in the list

  16. 16 Selection Structures • if… elif …else #! /usr/bin/env python • Ends with a “:” on that line myin = raw_input("Enter a number: ") • Blocks of code delineated by x = int(myin) indentation (via tabs) if x > 10: print “Number is greater than 10” elif x < 10: print “Number is less than 10” else: print “Number is equal to 10”

  17. 17 Iterative Structures • while <cond>: #! /usr/bin/env python • Again code is delineated by myin = raw_input("Enter a number: ") indentation i = 1 while i < int(myin): if i % 5 == 0: print i i += 1

Recommend


More recommend