Slide 1

Slide 1 text

An Introduction to the Python Programming Language Presented by Kapil Agarwal & Shubham Jain IMG, IIT Roorkee

Slide 2

Slide 2 text

Presentation Overview • Running Python • Data Types • Control Flow Structures • Functions • Classes • Exception Handling • Built in functions

Slide 3

Slide 3 text

Running Python

Slide 4

Slide 4 text

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!’

Slide 5

Slide 5 text

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!'

Slide 6

Slide 6 text

Python Overview • Programs are composed of modules • Modules contain statements • Statements contain expressions • Expressions create and process objects

Slide 7

Slide 7 text

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 >>>

Slide 8

Slide 8 text

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

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

Comments in Python >>> 'this will print' 'this will print' >>> #'this will not' >>> The ‘#’ starts a line comment Used in python files for commenting

Slide 11

Slide 11 text

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.

Slide 12

Slide 12 text

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

Slide 13

Slide 13 text

Built-in data types

Slide 14

Slide 14 text

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 >>>

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

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)

Slide 18

Slide 18 text

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

Slide 19

Slide 19 text

No content

Slide 20

Slide 20 text

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'

Slide 21

Slide 21 text

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!'

Slide 22

Slide 22 text

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'

Slide 23

Slide 23 text

String Formatting • Similar to C’s printf • % • 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' >>>

Slide 24

Slide 24 text

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']

Slide 25

Slide 25 text

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]

Slide 26

Slide 26 text

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,) >>>

Slide 27

Slide 27 text

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]

Slide 28

Slide 28 text

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]}

Slide 29

Slide 29 text

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'}

Slide 30

Slide 30 text

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}

Slide 31

Slide 31 text

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 ) .

Slide 32

Slide 32 text

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}:

Slide 33

Slide 33 text

No content

Slide 34

Slide 34 text

No content

Slide 35

Slide 35 text

No content

Slide 36

Slide 36 text

No content

Slide 37

Slide 37 text

No content

Slide 38

Slide 38 text

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

Slide 39

Slide 39 text

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

Slide 40

Slide 40 text

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.

Slide 41

Slide 41 text

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!

Slide 42

Slide 42 text

Modules • The highest level structure of Python • Each file is a module • Each has its own namespace

Slide 43

Slide 43 text

Modules: Imports import mymodule Brings all elements of mymodule in, but must refer to as mymodule. from mymodule import x Imports x from mymodule right into this namespace from mymodule import * Imports all elements of mymodule into this namespace

Slide 44

Slide 44 text

Control Flow

Slide 45

Slide 45 text

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

Slide 46

Slide 46 text

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

Slide 47

Slide 47 text

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

Slide 48

Slide 48 text

Loop Control Statements break Jumps out of the closest enclosing loop continue Jumps to the top of the closest enclosing loop

Slide 49

Slide 49 text

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

Slide 50

Slide 50 text

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

Slide 51

Slide 51 text

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

Slide 52

Slide 52 text

Functions

Slide 53

Slide 53 text

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'

Slide 54

Slide 54 text

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

Slide 55

Slide 55 text

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 >>> x() hello >>> x = 'blah' >>> x 'blah'

Slide 56

Slide 56 text

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

Slide 57

Slide 57 text

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

Slide 58

Slide 58 text

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 5

Slide 59

Slide 59 text

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

Slide 60

Slide 60 text

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

Slide 61

Slide 61 text

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

Slide 62

Slide 62 text

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

Slide 63

Slide 63 text

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]

Slide 64

Slide 64 text

Classes

Slide 65

Slide 65 text

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

Slide 66

Slide 66 text

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

Slide 67

Slide 67 text

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

Slide 68

Slide 68 text

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

Slide 69

Slide 69 text

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

Slide 70

Slide 70 text

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

Slide 71

Slide 71 text

Instance Variables • Created as they are assigned • Referenced as self.

Slide 72

Slide 72 text

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

Slide 73

Slide 73 text

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)

Slide 74

Slide 74 text

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

Slide 75

Slide 75 text

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'

Slide 76

Slide 76 text

Exception Handling

Slide 77

Slide 77 text

Exception Handling

Slide 78

Slide 78 text

Built-in functions

Slide 79

Slide 79 text

No content

Slide 80

Slide 80 text

No content

Slide 81

Slide 81 text

No content

Slide 82

Slide 82 text

No content

Slide 83

Slide 83 text

No content

Slide 84

Slide 84 text

No content

Slide 85

Slide 85 text

No content

Slide 86

Slide 86 text

No content

Slide 87

Slide 87 text

Again Classes

Slide 88

Slide 88 text

No content

Slide 89

Slide 89 text

No content

Slide 90

Slide 90 text

No content

Slide 91

Slide 91 text

No content

Slide 92

Slide 92 text

No content

Slide 93

Slide 93 text

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

Slide 94

Slide 94 text

• II. • Make a function to check whether a given number is prime or not.

Slide 95

Slide 95 text

• 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

Slide 96

Slide 96 text

• 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

Slide 97

Slide 97 text

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!"

Slide 98

Slide 98 text

• VI. • Find Lowest Common Multiple(LCM) of 2 given integers.

Slide 99

Slide 99 text

• 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