Introduction to Python
Python
! ! ! !
Highly popular language Easy to pick up and start Supported by large number of libraries/packages Highly popular among 'Information Retrieval' group who parse large amount of data
Overview of the talk
! ! ! !
Running python Data structures Functions Tips
Running Python
!
! ! ! ! !
If you are using Mac or Linux>python Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>
You need to install it on Windows
Hello, World!
! ! !
>python >>> print Hello, World! World's shortest Hello, World! program
Importing Packages
! ! !
These are software libraries written by someone else Similar to Java packages Remember following?
! !
import java.util.*; (from Java) #include <stdio.h> (from C)
Importing Packages: Example
!
! ! ! ! ! ! ! !
Two packages 'os.path' and 'os'
>>> import os >>> import os.path >>> os.getcwd() '/Users/aparate/Downloads' >>> os.path.isfile(os.getcwd()) False >>> os.path.isdir(os.getcwd()) True
!
! ! !
Using alternative names
>>> import os.path as mypath >>> mypath.isdir(os.getcwd()) True
Documentation? search 'python <packagename> package'
Declaring variables
! ! ! ! ! ! ! ! !
>>> x = 'This is a string' >>> print x This is a string >>> x = 0 >>> print (x+1) 1 >>> x = 0.0 >>> print (x+1) 1.0
Variables are dynamic in nature
Lists
! ! !
Similar to arrays in Java and C But much more powerful! Look at following Java code:
!
int [ ] array = new int [] {1, 2, 3, 4, 5}
! !
Look at following python code:
!
array = [1 ,2, '3', 'string 2', 4.5]
Different data types can be present in same array!
Lists
! ! ! ! ! ! !
array = [1 ,2, '3', 'string 2', 4.5] print array[0] 1 print array[3] 'string 2' print array[5] IndexError: list index out of range
Iterating through lists
! ! ! ! !
Or how to read each element in list Method I: li = [1 ,2, '3', 'string 2', 4.5] for item in li: print item
Iterating through lists
! !
Method II:
len(): gives length of list ! range(n): ! [0, 1, 2, ..., n-1]
! ! !
li = [1 ,2, '3', 'string 2', 4.5] for i in range(len(li)): print li[i]
Merging lists
! ! ! ! ! ! ! ! !
list1 = ['a' , 'b', 'c'] print list1 ['a', 'b', 'c'] list2 = ['d','e','f'] print list2 ['d','e','f'] list1.extend(list2) print list1 ['a', 'b', 'c', 'd', 'e', 'f']
Delete element in lists if it exists
! ! ! ! ! ! ! !
list1 = ['a' , 'b', 'c'] print list1 ['a', 'b', 'c'] element = 'a' if element in list1: list1.remove(element) print list1 ['b','c']
Dictionaries
! ! ! !
Similar to HashTable in Java It's a list of <key,value> pairs. Similar to word,synonym pair in english dictionary. Example:
!
d = {"name":"Abhinav", "position":"TA", "course":445}
Dictionaries
! ! ! ! ! ! ! ! ! !
d = {"name":"Abhinav", "position":"TA", "course":445} print d[name] Abhinav print d[course] 445 d[course] = 645 print d[course] 645 print d[last name] KeyError: 'last name'
Add/Delete in Dictionary
Addition/Update: d[10] = xyz print d[10] xyz Deletion del d[10] print d {'position': 'TA', 'name': 'Abhinav', 'course': 645}
Existence of key in Dictionary
>>> key = name >>> d = {"name":"Abhinav", "position":"TA", "course":445} >>> if key in d: >>> print d[key]
Iterating over dictionary
# Reading all the key,value pairs in dictionary >>> d = {"name":"Abhinav", "position":"TA", "course":445} >>> for key in d.keys(): >>> print d[key]
Merging dictionary
# Merging two dictionaries >>> d = {"name":"Abhinav", "position":"TA", "course":445} >>> d2 = {"semester":7} >>> d.update(d2) >>> d {'position': 'TA', 'semester': 7, 'name': 'Abhinav', 'course': 445}
Defining functions
# Print elements in list def printlist(mylist): for i in range(len(mylist)): print mylist[i] list1 = {'first', 'second'} printlist(list1)
Functions: Example 2
# Delete element with key 'name' in dictionary def deletename(mydict): if name in mydict: del mydict[name] return mydict
Functions: Example 2 continued
>>> dict1 = {"name":"Abhinav","course":445} >>> dict2 = deletename(dict1) >>> print dict2 {'course': 445} >>> print dict1 {'course': 445} >>> dict1 = {"name":"Abhinav","course":445} >>> dict2 = deletename(dict1.copy()) >>> print dict1 {'course': 445, 'name': 'Abhinav'} >>> print dict2 {'course': 445}
Some helpful functions
!
! ! ! !
append(): Adds one element to the list
>>> list1 = ['a','b','c'] >>> list1.append('d'); >>> list1 ['a', 'b', 'c', 'd']
! !
! !
Note the difference from merging list! deepcopy(): makes a copy of your list
>>> import copy >>> list2 = copy.deepcopy(list1)
A little hint for assignment
!
A Table is represented as list of dictionaries. ! Person = [ {'name':'Abhinav','age':26}, {'name':'Jane','age':21} ] ! In a list, each element is dictionary ! The column names in table are keys for dictionary ! You now know ! how to iterate and read list ! how to iterate and read dictionary ! how to add/delete elements in list and dictionary ! how to write functions ! You know all you need to do assignment!
Python files for assignment
! ! !
Write all your code in a file with .py extension: <your-login-id>.py It should stick to the format provided in starter code on edlab machine. Execute it as follows:
!
python <your-login-id>.py