PyTHON MONTH WORKSHOP
@
BCREC, DURGAPUR
contributors
Souradeep De (@desouradeep)
Avik Ghosh (@neonONtheRocks)
Subhendu Ghosh
Sudip Maji (@iamsudip258)
Atish Kumar (@atishnath123)
Bodhiswattwa Tewari (@ZubinZorro)
SOURADEEP DE
IRC Nick: souradeep
@desouradeep
github: github.com/desouradeep
FOSS CONTRIBUTOR :
CURRENTLY:
3rd Year CSE Student at BCREC, Durgapur
AVIK GHOSH
IRC Nick: avik
@neonONtheRocks@
github: github.com/ghoshavik
FOSS CONTRIBUTOR :
Python For You and Me, Kushal Das
CURRENTLY:
3rd Year CSE Student at BCREC, Durgapur and a part time creative writer
SUDIP MAJI
IRC Nick: iamsudip
@iamsudip258
github: github.com/iamsudip
FOSS CONTRIBUTOR :
Python For You and Me, Kushal Das
CURRENTLY:
3rd Year CSE Student at BCREC, Durgapur
BODHISWATTWA TEWARI
@ZubinZorro
IRC Nick: zubin
github: github.com/zubinz
FOSS CONTRIBUTOR:
Remote gcc compiler
CURRENTLY: 3rd Year CSE Student at BCREC, Durgapur
ATISH NATH KUMAR
IRC Nick: atish
@atishnath123
github: github.com/atishnathkumar
CURRENTLY:
3rd Year CSE Student at BCREC, Durgapur
python is simple
Hello World
How we do it in Java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
And in C
#include<stdio.h>
void main()
{
printf("Hello World!");
}
The Pythonic Way
Code directly in the interpreter:
>>> print "Hello World!" Hello World!
Execute from a file:
Open an editor and type :
#!/usr/bin/env python print "Hello World!"
Save the file as helloworld.py
Execute:
$ python helloworld.py
Hello World!
WHITESPACE AND INDENTATION
>>> a = 12 >>> a = 12 File "<stdin>", line 1 a = 12 ^ IndentationError: unexpected indent
assignments
Multiple Assignments
>>> a , b = 45, 54 >>> a 45 >>> b 54
We do not specify the datatype. We just assign, Python does the rest.
>>> a = 13 >>> b = 23 >>> a + b 36
Lets swap two numbers
The Usual Way
>>> a = 45 >>> b = 54 >>> c = a >>> a = b >>> b = c >>> print a, b 54 45
>>> a, b = b , a >>> print a, b 54 45
The Pythonic Way
type casting
>>> a = 45 >>> str(a) '45' >>> b = '121' >>> float(b) 121.0 >>> c = 23.43 >>> int(c) 23
READING INPUT
LETS TRY OUT A PROBLEM
A program to take an interger input.
>>> name = raw_input("Enter a name : ") Enter a string : Souradeep >>> name 'Souradeep'
>>> number = int(raw_input("Enter an integer: ")) >>> print number
control flow
-
if else
-
while
-
for
IF STRUCTURE
AN EXAMPLE
if expression: do this
>>> x = int(raw_input("Please enter an integer: ")) >>> if x < 0: ... x = 0 ... print 'Negative changed to zero' ... elif x == 0: ... print 'Zero' ... elif x == 1: ... print 'Single' ... else: ... print 'More'
WHILE STRUCTURE
AN EXAMPLE
>>> n = 0 >>> while n < 11: ... print n ... n += 1 ... 0 1 2 3 4 5 6 7 8 9 10
while condition: statement1 statement2
LETS REVISIT FIBONACCI SERIES
THE OUTPUT
>>> a, b = 0, 1 >>> while b < 100: ... print b ... a, b = b, a + b
1 1 2 3 5 8 13 21 34 55 89
FOR loop
Before diving into for loops, we should get acquainted with the range() function
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(2,10) [2, 3, 4, 5, 6, 7, 8, 9] >>> range(2, 10, 3) [2, 5, 8]
>>> for i in range(0, 5): ... print i 0 1 2 3 4
DATA STRUCTURES
-
List
-
Tuple
-
Dictionary
A Data structure is a way to store, retrieve and manipulate data
LISTS
A list is similar to an array but with much greater functionality.
a = [1, 2, 3]
a = ['as', 23, [1, 2, 3, 'a']]
(Can hold almost anything you'd wish, how's that for a change)
SOME List functions
>>> a [1, 1, 2, 7, 4, 5, 6]
>>> len(a) 7
>>> a.reverse() [6, 5, 4, 7, 2, 1]
>>> a.count(1) 2
>>> a.sort() [1, 1, 2, 4, 5, 6, 7]
>>> a.insert(2, 9) [1, 1, 9, 2, 4, 5, 6, 7]
>>> del a[-1] [1, 1, 9, 2, 4, 5, 6]
LOOPING ACROSS LISTS
Yeah, its that simple :)
>>> languages = ['Python', 'C', 'Java', 'Ruby'] >>> for i in languages: ... print i Python C Java Ruby
LETS IMPLEMENT STACK AND QUEUE USING LISTS
Stack (LIFO)
Queue (FIFO)
>>> a = [1, 2, 3, 4, 5] >>> a.append(1) >>> a [1, 2, 3, 4, 5, 1] >>> a.pop(0) 1 >>> a.pop(0) 2 >>> a [3, 4, 5, 1]
>>> a [1, 2, 3, 4, 5, 6] >>> a.pop() 6 >>> a.pop() 5 >>> a.append(34) >>> a [1, 2, 3, 4, 34]
tuple
Tuples are immutable data structures. Elements are seperated by a comma.
>>> a = 'Fedora', 'Debian', 'Kubuntu', 'Pardus' >>> a ('Fedora', 'Debian', 'Kubuntu', 'Pardus') >>> a[1] 'Debian' >>> for x in a: ... print x, ... Fedora Debian Kubuntu Pardus
DICTIONARIES
>>> data = {'name':'Souradeep De', 'dept':'CSE'} >>> data['name'] 'Souradeep De' >>> data['dept'] 'CSE'
Dictionaries are unordered set of key:value pairs, where keys are unique
>>> data['college'] = 'BCREC' >>> data {'dept': 'CSE', 'college': 'BCREC', 'name': 'Souradeep De'}
FUNCTIONS
Reusing the code as much as possible
def functionname(params): statement1 statement2
A small example:
>>> def sum(a, b): ... return a + b
revisiting palindrome function
>>> def palindrome(s): ... return s == s[::-1] >>> palindrome('abcd') False >>> palindrome('abccba'): True
SOME EXCITING STUFF
-
Downloading a File
-
Facebook status update
-
Sending email
-
Downloading PyCon US 2013 videos
- Web Crawler
No rocket science involved, only a few lines of code
DOWNLOADING A FILE
TASK: Download the ebook, Python for You and Me, Kushal Das.
Open the current directory and search for the file "pym.pdf"
1 | from urllib import urlretrieve 2 | urlretrieve('http://kushaldas.in/tmp/pym.pdf','pym.pdf')
FACEBOOK STATUS UPDATE
TASK: Posting a Status Update on your Facebook wall
1 | import fbconsole 2 | fbconsole.AUTH_SCOPE = ['publish_actions'] 3 | fbconsole.authenticate() 4 | fbconsole.post('/me/feed', {'message':'Python Rocks!!!'}) 5 | fbconsole.logout()
Visit you wall and see the post.
sending an email
TASK: Send an email from your gmail account.
1 | import smtplib 2 | server = smtplib.SMTP('smtp.gmail.com', 587)
3 | server.ehlo()
4 | server.starttls() 5 | server.login('yourEmailUsername', 'yourEmailPassword') 6 | message = 'Hi, \nPython is awesome. :)\nThanks.' 7 | server.sendmail("from.email@gmail.com", "to.email@example.com", message)
This is just an example, not the actual method of sending an email, since the email will lack a subject among other fields.
DOWNLOADING PYCON US 2013 VIDEOS
1 | from requests import get 2 | from feedparser import parse 3 | from urllib import urlretrieve 4 | from os import system 5 | 6 | req = get('http://pyvideo.org/category/33/pycon-us-2013/rss') 7 | dic = parse(req.text) 8 | for entry in dic['entries']: 9 | try: 10| video_link = entry.links[1]['href'] 11| print 'Downloading video', video_link 12| if video_link.startswith('https://www.youtube.com'): 13| download_link = 'youtube-dl -o "%(title)s.%(ext)s" -- restrict-filenames '+ video_link 14| system(download_link) 15| else: 16| download_link = video_link 17| file_name = video_link[52:video_link.find('?')] 18| urlretrieve(download_link, file_name) 19| except: 20| pass
WEB CRAWLER
TASK: Open a Firefox window and navigate to the Python Month page in PyCon India website
-
Open a Firefox Window
-
Go to google.com and search "pycon india"
-
Click the pycon india link
-
Go to the python month page
the crawler code
1 | from selenium import webdriver 2 | from selenium.webdriver.common.keys import Keys 3 | from time import sleep 4 | 5 | driver = webdriver.Firefox() # opens firefox 6 | driver.maximize_window() 7 | 8 | driver.get('http://google.com') 9 | assert "Google" in driver.title 10| elem = driver.find_element_by_xpath('//*[@id="gbqfq"]') 11| elem.send_keys("pycon india") # webdriver enters data in search bar 12| elem.send_keys(Keys.RETURN) # ENTER key press 13| sleep(2) 14| # Google search results loaded 15| elem = driver.find_element_by_xpath('//*[@id="rso"]/li/div/h3/a') 16| elem.send_keys(Keys.RETURN) # ENTER pressed on first link 17| sleep(2) 18| # PyCon India page loaded 19| elem = driver.find_element_by_xpath('/html/body/div/nav/ul/li[6]/a') 20| elem.send_keys(Keys.RETURN) # ENTER pressed on Python Month link 21| # Python Month page loaded
thank you :)
http://in.pycon.org/2013/python-month
Presentation Courtesy:
Souradeep De (souradeep.2011 AT gmail DOT com)
PYTHON MONTH WORKSHOP @ BCREC
By Souradeep De
PYTHON MONTH WORKSHOP @ BCREC
- 3,173