talk code

9

Click here to load reader

Upload: agiliq-solutions

Post on 06-May-2015

1.932 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Talk Code

Slide 1------------Python - why settle for snake oil when you can have the whole snake?

Slide 2------------* This is a workshop, not a talk.* You are expected to code along.* So pull out your laptops, and* Install python, ipython and komodo edit. (Or editor of your choice.)

Slide 3------------* Assume that you know programming in any language.* So we dont spend a lot of time explaining basics.* BUT, stop and ask if something doesn't make sense.* AND Definately Stop me if I am going too slow, too fast, or making no sense.

Slide 4------------* Python *

* Dynamically but strongly typed.* Very object oriented - everything is an object.* But pragmatic - Objects aren't everthing.* Allows various paradigms of programming - OO, procedural, functional.* Shallow learning curve, but powerful powerful capabilities avaialble, when youneed them.* import this* We will come back to this slide.

Slide 4.1-----------* Hello world *

>>> print "Hello World"

Slide 5-------------* Lets start *

* The control structures.* for, while, if, else, break, continue* -Yeah they are available, surprised?* We will use them in a moment, but after we see the data structures available.

Slide 6----------

* The data strcutures *

* List - Like ArrayList in Java* Tuple - Like List, but immutable* Dict - Like Hashmaps in Java

--Hid

In [1]: v1 = [1, 2, 3, 4, 5]

In [2]: v2 = (1, 2, 3, 4, 5)

Page 2: Talk Code

In [3]: v3 = {1:'a', 2:'b'}

In [4]: type(v1)Out[4]: <type 'list'>

In [5]: type(v2)Out[5]: <type 'tuple'>

In [6]: type(v3)Out[6]: <type 'dict'>

Slide 7-----------* The control structures. *

* For Loop* for el in iterable: [block statement]* the classic for loop* for (int i; i < n; i++){}* for i in range(n): #Work with i* while condition: [block]* break, continue. Normal operation - break out of current loop.

--Hidden--In [10]: for el in v1: ....: print el ....: ....: 12345

In [11]: x = 5

In [12]: while x < 100: ....: print x ....: x = x * 2 ....: ....: 510204080

Slide 8 --------------

Conditionals--------------*If: elif: else:*

* if condition: [block] else: [block]

Page 3: Talk Code

--Hidden--

In [15]: if f == 10: ....: print 'Ten' ....: else: ....: print 'Not 10' ....: ....: Ten

if f == 12: print 'Ten' else: print 'Not 10' Slide 9--------------

* The fizzbuzz test ** You have enough information now to write a solution* Problem statementWrite a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

--Hidden---Give time here

[Wrong]for i in range(1, 101): if i % 3 == 0: print 'fizz' elif i % 5 == 0: print 'buzz' elif i % 15 == 0: print 'fizzbuzz' else: print i [One sol]

for i in range(1, 101): if i % 15 == 0: print 'fizzbuzz' elif i % 3 == 0: print 'fizz' elif i % 5 == 0: print 'buzz' else: print i

Slide 10------------

* Functions *

def function_name(argument_list): [block] * Functions can have default value.

Page 4: Talk Code

def fizzbuzz(till=100, fizz='fizz', buzz='buzz'): #fizzbuzz code * Functions can have variable length values.

ex multiply all values passed to a function.

* Functions are first class - They are objects too. They can be passed to otherfunctions, assigned to variables etc.

--Hidden--In [33]: def func(): ....: pass ....:

In [34]: type(func)Out[34]: <type 'function'>

In [35]: def mult_all(*args): ....: i = 1 ....: for el in args: ....: i = i * el ....: ....: return i ....:

In [36]: mult_all(2, 3, 4, 5)Out[36]: 120

Slide 11-----------* Classes *

class ClassName(base_classes): [block] * Classes are first class too* They can be passed to function, and assigned to variables.

---Hiden---

class Accounts(object): def __init__(self, account_holder, initial_deposit): self.account_holder = account_holder self.money_available = initial_deposit self.history = [] def withdraw(self, amount): self.money_available = self.money_available - amount self.history.append('Withdrew %s'%amount) def deposit(self, amount): self.money_available = self.money_available + amount self.history.append('Deposited %s'%amount) def __str__(self): return "%s has %s available." % (self.account_holder, self.money_available) def __repr__(self): return str(self)

Page 5: Talk Code

Slide 12-----------

* Time for another problem *

* Project euler: problem 1

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000

--hidden--In [15]: sum = 0

In [16]: for i in range(1000): Display all 213 possibilities? (y or n)

In [16]: for i in range(1000): ....: if i % 3 == 0 or i % 5 == 0: ....: sum += i ....: ....:

In [18]: print sum-------> print(sum)233168

Slide 13-----------* Here comes the list comprehensions *

* The last sulotion was needlessly verbose* List comprehension: Take a list and transform it.* Standard list comrehension syntax - [expr(i) for i in iterable if condition]* List of all squares: [i*i for i in range(1,11)]* List of all squares of even numbers: [i*i for i in range(1,11) if i%2 == 0]* So solution to last problem is justsum([i*i for i in range(1,1001) if i%3 == 0 or i%5==0])

--Hidden--In [19]: [i*i for i in range(1,11)]Out[19]: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]In [1]: sum([i*i for i in range(1,1001) if i%3 == 0 or i%5==0])Out[1]: 156390386

Slide 14-----------*Some functional programming*

* List comprehensions are python way to do functional programming constructs* [function(i) for i in iterable if condition] is filter(func2, map(func1, iter))* Lets see how this list comprehension maps to functional concepts* Get the list of squares of even numbers

--Hidden--In [5]: filter(lambda x: x%2==0, map(lambda x: x ** 2, range(1, 11)))

Page 6: Talk Code

Out[5]: [4, 16, 36, 64, 100]

In [6]: [el*el for el in range(1, 11) if el%2 ==0]Out[6]: [4, 16, 36, 64, 100]

Slide 15--------------*File Handling*

* Open a file with - open('location') or file('location')* or give a mode - open('location', 'rw')* iterate asfor line in open_file.readlines(): print line#Or whatvere

orstring = open_file.read()

--Hidden--

In [8]: open_file = open('/home/shabda/python_talk/11.txt')

In [9]: for el in open_file.readlines(): ...: print el ...: break ...: ...: Project Gutenberg's Alice's Adventures in Wonderland, by Lewis Carroll

Slide 16--------------

*Some actual work*

Find the most commonly used word in the Alice in wonderland text.

--Hidden--Give time here

#!/usr/bin/env pythonfrom operator import itemgetter

open_file = open('/home/shabda/python_talk/11.txt')text = open_file.read()words = text.split()word_count = {}for word in words: if word in word_count: word_count[word] += 1 else: word_count[word] = 1 sorted_list = sorted(word_count.items(), key=itemgetter(1), reverse=True)print sorted_list[0]

Slide 17------------* Problems *

Page 7: Talk Code

* Ok, now you suggets some problems and lets solve them together.

Slide 18-------------* A tour of the standard library *

* Batteries included* math* datetime* string* re* random* os* pickle* Do a dir and see for yourself.

And a lot, lot morehttp://docs.python.org/library/

--hidden--Spend time here

In [14]: math.cos(math.pi)Out[14]: -1.0

In [9]: datetime.date.today() > datetime.date(2008, 9, 12)Out[9]: True

In [18]: string.capitalize('python is a programming language.')Out[18]: 'Python is a programming language.'

In [19]: import random

In [20]: random.choice(['ubuntu', 'redhat', 'xandros'])Out[20]: 'xandros'

In [21]: random.choice(['ubuntu', 'redhat', 'xandros'])Out[21]: 'ubuntu'

Slide 19-------------

* Back to slide 4 *

* Dynamically but strongly typed.* Very object oriented - everything is an object.* But pragmatic - Objects aren't everthing.* Allows various paradigms of programming - OO, procedural, functional.* Shallow learning curve, but powerful powerful capabilities avaialble, when youneed them.* import this

--Hidden--Explain.

* Slide 20 *---------------* Decorators *

Page 8: Talk Code

Syntacting sugar forfoo_func =docorator_func(foo_func)

--Hidden--

In [1]: def good_function(): ...: print 'I am a good function' ...: ...:

In [2]: def decorator(orig_func): ...: def bad_func(): ...: print 'I am a bad function' ...: return bad_func ...:

In [3]: good_function = decorator(good_function)

In [4]: good_function()I am a bad function

In [5]: @decorator ....: def good_function2(): ....: print 'I am a good function' ....: ....:

In [6]: good_function2()I am a bad function

#!/usr/bin/env python

def is_val_positive_deco(orig_func): def temp_func(val): if val < 0: return 0 else: return orig_func(val) return temp_func

@is_val_positive_decodef sqrt(val): import math return math.pow(val, (1.0/2))

print sqrt(-1)print sqrt(4)

Slide 21---------------* Web development with Python *

* Many useful frameworks* Django* GAE* Turbogears* We recommend Django - Most actively developed and largest community participation

Slide 22

Page 9: Talk Code

----------*If we have time** PIL - Image Manipulation* Mechanize - Browser automation* Beautiful Soup - Html extraction.

Slide 23-------------* Resources *python.orgdiveintopython.orguswaretech.com/blog

Slide 24----------* Thank You. *You can give feedback, ask questions at [email protected]