Upgrade to Pro — share decks privately, control downloads, hide ads and more …

15-437 Python

ThierrySans
September 10, 2013

15-437 Python

ThierrySans

September 10, 2013
Tweet

More Decks by ThierrySans

Other Decks in Education

Transcript

  1. What Java is like class HelloWorld { static public void

    main( String args[] ) { System.out.println( "Hello World!" ); } }
  2. Interacting with Python • Interactive shell • Files • Executable

    files $ python >>> print "Hello World" $ python helloWorld.py $ chmod +x helloWorld.py $ ./helloWorld.py #! /usr/bin/env python print "Hello World" helloWorld.py print "Hello World" helloWorld.py
  3. Integers and Floats • Integers • Floats 2 + 3

    # returns 5 7 / 3 # returns 2 7 % 3 # returns 1 3. / 2. # returns 0.5 3. / 2 # returns 0.5 float(1) / 2 # returns 5
  4. Booleans • Values and operators • Equality and inequality True

    # is actually 1 False # is actually 0 a and b a or b not a a == b a != b
  5. Strings “hello” + “world” # returns “helloworld” “hello” * 3

    # returns “hellohellohello” “hello”[0] # returns “h” “hello”[1:4] # returns “ell” “hello”[-1] # returns “o”, last element len(”hello”) # returns 5 ”sml” < ”python” # returns 0 (False) ”e” in ”hello” # returns 1 (True) ”\”hello\”” # returns “hello”
  6. Tuples and named tuples () # returns () (“hello”, 3)

    # returns (“hello”,3) (“hello, 3)[0] # returns “hello”
  7. Lists a = [“I”, “have”, 3, “QAR”, [“in”,”my”,”pocket”]] a +

    [“!”] # concatenation a[0] # indexing a[1:4] # slicing len(a) # length del(a[-1]) # delete range(3) # returns [0,1,2] range(3:5) # returns [3,4]
  8. Object-style methods a.append(5) # inserts 5 at the end a.insert(0,5)

    # inserts 5 at index 0 (shift) a.pop() # returns the last element # and deletes it a.pop(0) # returns the element at index i # and deletes it (shift) a.reverse() # reverse a.sort() # sort
  9. Dictionaries (aka associative arrays or hashtables) a = {“name”:“John”, “age”:

    5} a[“name”] # returns “john” (lookup) a[“address”] # returns KeyError exception del(a[“name”]) # delete a[“city”]=”doha” # insert a[“city”]=”paris” # modify • Values can be anything (mix and match) • But keys must be immutable and of the same type
  10. Object-style methods a.keys() # [“age”,”city”] a.values # [5,”paris”] a.items() #

    [(“age”,5),(“city”,“paris”)] a.has_key(“name”) # returns false
  11. Variable • A variable is declared when first assigned to

    a value • Unknown variables raise exceptions
  12. Types • No explicit type declaration • But implicit typing

    • Wrong typed expressions raise exceptions
  13. References • Modifying an immutable variable • A new reference

    is created • Modifying a mutable variable • The value pointed by the reference is changed
  14. Example def gcd(a,b): “greatest common divisor” while a!=0: a,b =

    b % a, a return b gcd(12,20) # returns 4 gcd.__doc__ # returns “greatest common divisor”
  15. Function vs Procedure def name(arg1,arg2): statements return # defines a

    procedure def name(arg1,arg2): statements return something # defines a function
  16. Catching exception def divisionBy0(x) try: print 1 / x except

    ZeroDivisionError, message: print “Can’t divide by zero:”, message else: print “Can divide by zero” finally: print “done”
  17. Defining a class class Stack: "A well-known data structure..." def

    __init__(self): self.items = [] # constructor def push(self, x): self.items.append(x) def pop(self): x = self.items[-1] # what happens if it’s empty? del self.items[-1] return x def empty(self): return len(self.items) == 0 # Boolean result
  18. Instantiating an object x = Stack() # new object of

    type Stack x.empty() # returns True x.push(1) x.empty() # returns false x.push("hello") x.pop() # returns “hello”
  19. Module made easy • A module is a collection of

    classes, functions and variables • Creating a module • Create a file name stack.py (containing the stack definition defined previously) • Using a module import stack # import all definitions in stack x = stack.Stack() from stack import Stack # import the definition of Stack only x = stack.Stack() Or
  20. Executing a module # Fibonacci numbers module def fib(n): #

    write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b if __name__ == "__main__": import sys fib(int(sys.argv[1])) fibo.py Execute the module $ python fibo.py 4
  21. Python or not Python? ✓ Syntax friendly ✓ Good libraries

    ๏ Dynamically typed (hard to debug)