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

Python Lecture

IMG
March 12, 2013

Python Lecture

A lecture given on Introduction to Python programming language by Kapil Agarwal & Shubham Jain.

IMG

March 12, 2013
Tweet

More Decks by IMG

Other Decks in Programming

Transcript

  1. Presentation Overview • Running Python • Data Types • Control

    Flow Structures • Functions • Classes • Exception Handling • Built in functions
  2. Hello World gen@chaos:~$ python >>> >>> 'hello world!' 'hello world!'

    >>>print 'hello world!' hello world! I. •Open a terminal window and type “python” •At the prompt type ‘hello world!’
  3. Hello World gen@chaos:~$ vi hello.py gen@chaos:~$ ./hello.py hello world! II.

    Creating a file #!/usr/bin/python print 'hello world!' gen@chaos:~$ vi hello.py gen@chaos:~$ python hello.py hello world! print 'hello world!'
  4. Python Overview • Programs are composed of modules • Modules

    contain statements • Statements contain expressions • Expressions create and process objects
  5. The Python Interpreter •Python is an interpreted language •The interpreter

    provides an interactive environment to play with the language •Results of expressions are printed on the screen >>> 3 + 7 10 >>> 3 < 15 True >>> 'print me' 'print me' >>> print 'print me' print me >>>
  6. Output: The print Statement >>> print 'hello' hello >>> print

    'hello', 'there' hello there •Elements separated by commas print with a space between them •A comma at the end of the statement (print ‘hello’,) will not print a newline character
  7. Keywords and del for is raise assert elif from lambda

    return break else global not try class except if or while continue exec import pass with def finally in print yield
  8. Comments in Python >>> 'this will print' 'this will print'

    >>> #'this will not' >>> The ‘#’ starts a line comment Used in python files for commenting
  9. Variables • Are not declared, just assigned • The variable

    is created the first time you assign it a value • Are references to objects • Type information is with the object, not the reference • Everything in Python is an object • To assign a variable to null value, assign ‘None’ to it.
  10. Everything is an object??? • Everything means everything, including functions

    and classes >>> x = 7 >>> x 7 >>> x = 'hello' >>> x 'hello' >>> Type info is with the object
  11. Numbers: Integers • Integer(type int) – the equivalent of a

    C long • Long Integer(type long) – an unbounded integer value. Newer versions of Python will automatically convert to a long integer if you overflow a normal one >>> 132224 132224 >>> 132323 ** 2 17509376329L >>>
  12. Numbers: Floating Point • type float • int(x) returns x

    to an integer • float(x) returns x to a floating point • The interpreter shows a lot of digits, including the variance in floating point • To avoid this use “print” >>> 1.23232 1.2323200000000001 >>> print 1.23232 1.23232 >>> 1.3E7 13000000.0 >>> int(2.0) 2 >>> float(2) 2.0
  13. Numbers: Complex • type complex • Built into Python •

    Same operations are supported as integer and float >>> x = 3 + 2j >>> y = -1j >>> x + y (3+1j) >>> x * y (2-3j) >>>x.real 3 >>>x.imag 2
  14. Booleans • type bool • 0 and None are false

    • Everything else is true • True and False are aliases for 1 and 0 respectively (added in more recent versions of Python)
  15. Boolean Expressions • Compound boolean expressions short circuit • and

    and or return one of the elements in the expression • Note that when None is returned the interpreter does not print anything >>> True and False False >>> False or True True >>> 7 and 14 14 >>> None and 2 >>> None or 2 2
  16. Strings • Type str & unicode • Strings are immutable

    • There is no char type like in C++ or Java • + is overloaded to do concatenation >>> x = 'hello' >>> x = x + ' there' >>> x 'hello there'
  17. String Literals: Many Kinds •"a string enclosed by double quotes"

    •'another string delimited by single quotes and with a " inside' •'''a string containing embedded newlines and quote (') marks, can be delimited with triple quotes.''' •""" may also use 3- double quotes as delimiters """ •b"An 8-bit string" - A bytes instance, a forward- compatible form for an 8-bit string' •u'a unicode string' •r'a raw string where \ are kept (literalized): handy for regular expressions and windows paths!'
  18. Substrings and Methods >>> s = '012345' >>> s[3] '3'

    >>> s[1:4] '123' >>> s[2:] '2345' >>> s[:4] '0123' >>> s[-2] '4' •len(String) – returns the number of characters in the String •str(Object) – returns a String representation of the Object >>> len(x) 6 >>> str(10.3) '10.3'
  19. String Formatting • Similar to C’s printf • <formatted string>

    % <elements to insert> • Can usually just use %s for everything, it will convert the object to its String representation. >>> "One, %d, three" % 2 'One, 2, three' >>> "%d, two, %s" % (1,3) '1, two, 3' >>> "%s two %s" % (1, 'three') '1 two three' >>>
  20. Lists • type list • Ordered collection of data •

    Data can be different types • Lists are mutable • Issues with shared references and mutability • Same subset operations as Strings >>> x = [1,'hello', (3 + 2j)] >>> x [1, 'hello', (3+2j)] >>> x[2] (3+2j) >>> x[0:2] [1, 'hello']
  21. Lists: Modifying Content • x[i] = a reassigns the ith

    element to the value a • Since x and y point to the same list object, both are changed • Append also modifies the list >>> x = [1,2,3] >>> y = x >>> x[1] = 15 >>> x [1, 15, 3] >>> y [1, 15, 3] >>> x.append(12) >>> y [1, 15, 3, 12]
  22. Tuples • type tuple • Tuples are immutable versions of

    lists • One strange point is the format to make a tuple with one element (the ‘,’ is needed to differentiate from the mathematical expression (2) >>> x = (1,2,3) >>> x[1:] (2, 3) >>> y = (2,) >>> y (2,) >>>
  23. Dictionaries • type dict • A set of key-value pairs

    • Dictionaries are mutable >>> d = {1 : 'hello', 'two' : 42, 'blah' : [1,2,3]} >>> d {1: 'hello', 'two': 42, 'blah': [1, 2, 3]} >>> d['blah'] [1, 2, 3]
  24. Dictionaries: Add/Modify • Entries can be changed by assigning to

    that entry • Assigning to a key that does not exist adds an entry >>> d {1: 'hello', 'two': 42, 'blah': [1, 2, 3]} >>> d['two'] = 99 >>> d {1: 'hello', 'two': 99, 'blah': [1, 2, 3]} >>> d[7] = 'new entry' >>> d {1: 'hello', 7: 'new entry', 'two': 99, 'blah': [1, 2, 3]}
  25. Dictionaries: Deleting Elements • The del keyword deletes an element

    from a dictionary >>> d {1: 'hello', 2: 'there', 10: 'world'} >>> del(d[2]) >>> d {1: 'hello', 10: 'world'}
  26. Copying Dictionaries and Lists • The built-in list function will

    copy a list. • The dictionary has a method called copy. >>> l1 = [1] >>> l2 = list(l1) >>> l1[0] = 22 >>> l1 [22] >>> l2 [1] >>> d = {1 : 10} >>> d2 = d.copy() >>> d[1] = 22 >>> d {1: 22} >>> d2 {1: 10}
  27. Data Type Wrap Up • Lists, Tuples, and Dictionaries can

    store any type (including other lists, tuples, and dictionaries!). • lists and dictionaries are mutable. • int (&basic numeric types) , strings and tuples are immutable . • dict keys can be of any hashable data (strings, int are hashable ,lists are not ) .
  28. Data Type Wrap Up • Integers: 2323, 3234L • Floating

    Point: 32.3, 3.1E2 • Complex: 3 + 2j, 1j • Lists: [ 1,2,3] • Tuples: (1,2,3) • Dictionaries: {‘hello’ : ‘there’, 2 : 15}:
  29. Files: Input built in type file input = open(‘data’, ‘r’)

    Open the file for input S = input.read() Read whole file into one String S = input.read(N) Reads N bytes (N >= 1) L = input.readlines() Returns a list of line strings
  30. Files: Output output = open(‘data’, ‘w’) Open the file for

    writing output.write(S) Writes the string S to file output.writelines(L) Writes each of the strings in list L to file output.close() Manual close
  31. Input • The raw_input(string) method returns a line of user

    input as a string • The parameter is used as a prompt • The string can be converted by using the conversion methods int(string), float(string), etc.
  32. Input: Example print "What's your name?" name = raw_input(">") print

    "What year were you born?" birthyear = int(raw_input(">")) print "Hi %s! You are %d years old!" % (name, 2005 - birthyear) ~: python input.py What's your name? >Michael What year were you born? >1980 Hi Michael! You are 25 years old!
  33. Modules • The highest level structure of Python • Each

    file is a module • Each has its own namespace
  34. Modules: Imports import mymodule Brings all elements of mymodule in,

    but must refer to as mymodule.<elem> from mymodule import x Imports x from mymodule right into this namespace from mymodule import * Imports all elements of mymodule into this namespace
  35. If Statements x = 22 if x < 15 :

    print 'first clause' elif x < 25 : print 'second clause' else : print 'the else' In file ifstatement.py >>> import ifstatement second clause >>> In interpreter
  36. No Braces??? • Python uses indentation instead of braces to

    determine the scope of expressions • All lines must be indented the same amount to be part of the scope (or indented more if part of an inner scope) • This forces the programmer to use proper indentation since the indenting is part of the program! • 4 bytes are used for indentation by convention
  37. While Loops x = 1 while x < 10 :

    print x x = x + 1 >>> import whileloop 1 2 3 4 5 6 7 8 9 >>> In whileloop.py In interpreter
  38. Loop Control Statements break Jumps out of the closest enclosing

    loop continue Jumps to the top of the closest enclosing loop
  39. The Loop Else Clause • The optional else clause runs

    only if the loop exits normally (not by break) x = 1 while x < 3 : print x x = x + 1 else: print 'hello' ~: python whileelse.py 1 2 hello Run from the command line In whileelse.py
  40. The Loop Else Clause x = 1 while x <

    5 : print x x = x + 1 break else : print 'i got here' ~: python whileelse2.py 1 whileelse2.py
  41. For Loops • Similar to perl forloops, iterating through a

    list of values • Forloops also have the optional else clause ~: python forloop.py 1 7 13 2 for x in [1,7,13,2] : print x forloop.py
  42. Function Basics def max(x,y) : if x < y :

    return x else : return y >>> import functionbasics >>> max(3,5) 5 >>> max('hello', 'there') 'there' >>> max(3, 'hello') 'hello'
  43. Function Not-So-Basics • Functions are first class objects o Can

    be assigned to a variable o Can be passed as a parameter o Can be returned from a function • Functions are treated like any other variable in python, the def statement simply assigns a function to a variable
  44. Functions as Variables • Functions are objects • The same

    reference rules hold for them as for other objects >>> x = 10 >>> x 10 >>> def x () : ... print 'hello' >>> x <function x at 0x619f0> >>> x() hello >>> x = 'blah' >>> x 'blah'
  45. Functions: As Parameters def foo(f, a) : return f(a) def

    bar(x) : retun x * x >>> from funcasparam import * >>> foo(bar, 3) 9 •The function foo takes two parameters and applies the first as a function with the second as its parameter
  46. Functions: In Functions • Since they are like any other

    object, you can have functions inside functions def foo (x,y) : def bar (z) : return z * 2 return bar(x) + y >>> from funcinfunc import * >>> foo(2,3) 7
  47. Functions Returning Functions def foo (x) : def bar(y) :

    return x + y return bar # main f = foo(3) print f print f(2) ~: python funcreturnfunc.py <function bar at 0x612b0> 5
  48. Defaults parameters • Can assign default values to parameters •

    They are overridden if a parameter is given for them • The type of the default doesn’t limit the type of a parameter >>> def foo(x = 3) : ... print x ... >>> foo() 3 >>> foo(10) 10 >>> foo('hello') hello
  49. Named arguments • Can specify the name of the parameter

    to set • Any positional arguments must come before named ones in a call >>> def foo (a,b,c) : ... print a, b, c ... >>> foo(c = 10, a = 2, b = 14) 2 14 10 >>> foo(3, c = 2, b = 19) 3 19 2
  50. Anonymous Functions • The lambda returns a function • The

    body can only be a simple expression, not complex statements >>> f = lambda x,y : x + y >>> f(2,3) 5 >>> l = ['one', lambda x : x * x, 3] >>> l[1](4) 16
  51. pass keyword • Defines null body to be defined in

    future • Used with functions, if, else, while, for, class etc. >>>def f(a,b): … pass >>>while c<12: … pass
  52. global keyword global name1 [, name2] • Names are from

    global scope (usually meaning from module) rather than local (usually meaning only in function). >>>a = [1,2] >>>def foo(): … global a … a += [4] >>>foo() [1,2,4]
  53. Classes • A collection of data and methods that act

    on that data • But in python functions are basically just data! • Classes themselves are objects • Every object in python has its type class • New Style classes have object as base class
  54. Class Syntax • Every method in a class takes a

    self-pointer as the first parameter (self as convention) like this in java or C++ • __init__ is a builtin function that you override as the constructor >>> from classbasic import * >>> x = myclass(3) >>> x.printit() 3 class myclass : def __init__(self, val) : self.x = val def printit(self) : print self.x
  55. Class Method Calls • Self is automatically added as the

    first parameter when a method is called on an instance of a class • Internally self must be explicitly passed
  56. Class Inheritance • Super classes are listed in brackets after

    the name of the class • Python allows multiple inheritance • Name resolution is bottom to top, left to right
  57. Class Inheritance: Example >>> from classinherit import * >>> x

    = c3() >>> obj = c3() >>> obj.z 2 >>> obj.x 10 >>> obj.y 15 class c1 : x = 10 class c2 : x = 20 y = 15 class c3(c1,c2) : z = 2
  58. Explicit Call to a Super-class Method class c2 (c1) :

    def __init__(self, x, y) : c1.__init__(self, x) self.y = y def foo(self) : c1.foo(self) print self.y class c1 : def __init__(self, x) : self.x = x def foo(self) : print self.x >>> obj = c2(4,5) >>> obj.foo() 4 5
  59. Classes as Objects • Classes exist as objects and contain

    all of there own variables • Name resolution starts looking in the instance of the class for a variable, then walks up the inheritance tree • Variables don’t exist in the instance until they are assigned there
  60. Classes as Objects: Example >>> class myclass : ... x

    = 10 ... >>> a = myclass() >>> b = myclass() >>> a.x, b.x, myclass.x (10, 10, 10) >>> a.x = 15 >>> a.x, b.x, myclass.x (15, 10, 10) >>> myclass.x = 20 >>> a.x, b.x, myclass.x (15, 20, 20) >>> a.x = myclass.x >>> a.x, b.x, myclass.x (20, 20, 20) >>> myclass.x = 99 >>> a.x, b.x, myclass.x (20, 99, 99)
  61. Docstrings • “triple-quote” strings at the beginning of an object

    • Creates the __doc__ variable of the object """docstring of module""" class myclass : """A class that really does nothing but demonstrate docstrings""" def foo () : """and a useless method for the same purpose""" print 'hi
  62. Docstrings: Example >>> import docstrings >>> docstrings.__doc__ 'docstring of module'

    >>> docstrings.myclass.__doc__ 'A class that really does nothing but\ndemonstrate docstrings' >>> docstrings.myclass.foo.__doc__ 'and a useless method for the same purpose'
  63. I. We want to make a row of bricks that

    is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks. This is a little harder than it looks and can be done without any loops. make_bricks(3, 1, 8) : True make_bricks(3, 1, 9) : False make_bricks(3, 2, 10) : True
  64. • II. • Make a function to check whether a

    given number is prime or not.
  65. • III. • Given two strings, return True if either

    of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: s.lower() returns the lowercase version of a string. • end_other('Hiabc', 'abc') : True • end_other('AbC', 'HiaBc') : True • end_other('abc', 'abXabc') : True
  66. • IV. • Return the "centered" average of an array

    of ints, which we'll say is the mean average of the values, except not counting the largest and smallest values in the array. Use int division to produce the final average. You may assume that the array is length 3 or more. • centered_average([1, 2, 3, 4, 100]) : 3 • centered_average([1, 1, 5, 5, 10, 8, 7]) : 5 • centered_average([-10, -4, -2, -4, -2, 0]) : -3
  67. V • Define a simple "spelling correction" function correct() that

    takes a string and sees to it that 1) two or more occurrences of the space character is compressed into one, and 2) inserts an extra space after a period if the period is directly followed by a letter. • E.g. correct("This is very funny and cool.Indeed!") should return • "This is very funny and cool. Indeed!"
  68. • VII. • Return True if the given string contains

    an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not. • xyz_there('abcxyz') : True • xyz_there('abc.xyz') : False • xyz_there('xyz.abc') : True