SlideShare a Scribd company logo
1 of 9
Download to read offline
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 you
need 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)
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
   ....:
   ....:
1
2
3
4
5

In [11]: x = 5

In [12]: while x < 100:
   ....:     print x
   ....:     x = x * 2
   ....:
   ....:
5
10
20
40
80

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

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

*   if condition:
        [block]
    else:
        [block]
--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 statement
Write 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.
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 other
functions, 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)
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 just
sum([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)))
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 as
for line in open_file.readlines():
    print line#Or whatvere

or
string = 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 python
from 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 *
* 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 more
http://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 you
need them.
* import this

--Hidden--
Explain.

* Slide 20 *
---------------
* Decorators *
Syntacting sugar for
foo_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_deco
def 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
----------
*If we have time*
* PIL - Image Manipulation
* Mechanize - Browser automation
* Beautiful Soup - Html extraction.

Slide 23
-------------
* Resources *
python.org
diveintopython.org
uswaretech.com/blog

Slide 24
----------
* Thank You. *
You can give feedback, ask questions at shabda@uswaretech.com

More Related Content

What's hot

Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a ElixirSvet Ivantchev
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
 
Dts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinDts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinAhmad Arif Faizin
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?Adam Dudczak
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладкаDEVTYPE
 
Design Pattern Observations
Design Pattern ObservationsDesign Pattern Observations
Design Pattern ObservationsDmitri Nesteruk
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedSusan Potter
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScriptGarth Gilmour
 
The best language in the world
The best language in the worldThe best language in the world
The best language in the worldDavid Muñoz Díaz
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with PythonHan Lee
 
The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196Mahmoud Samir Fayed
 
T3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerT3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerDavid Muñoz Díaz
 
Being functional in PHP (PHPDay Italy 2016)
Being functional in PHP (PHPDay Italy 2016)Being functional in PHP (PHPDay Italy 2016)
Being functional in PHP (PHPDay Italy 2016)David de Boer
 

What's hot (20)

Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
Dts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinDts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlin
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
 
Design Pattern Observations
Design Pattern ObservationsDesign Pattern Observations
Design Pattern Observations
 
PythonOOP
PythonOOPPythonOOP
PythonOOP
 
Collection Core Concept
Collection Core ConceptCollection Core Concept
Collection Core Concept
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids Applied
 
C++ L01-Variables
C++ L01-VariablesC++ L01-Variables
C++ L01-Variables
 
Python
PythonPython
Python
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
The best language in the world
The best language in the worldThe best language in the world
The best language in the world
 
Why Haskell
Why HaskellWhy Haskell
Why Haskell
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
 
The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196
 
T3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerT3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmer
 
C++ L04-Array+String
C++ L04-Array+StringC++ L04-Array+String
C++ L04-Array+String
 
Being functional in PHP (PHPDay Italy 2016)
Being functional in PHP (PHPDay Italy 2016)Being functional in PHP (PHPDay Italy 2016)
Being functional in PHP (PHPDay Italy 2016)
 

Similar to Talk Code

A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsMichael Pirnat
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnArnaud Joly
 
The Ring programming language version 1.5 book - Part 5 of 31
The Ring programming language version 1.5 book - Part 5 of 31The Ring programming language version 1.5 book - Part 5 of 31
The Ring programming language version 1.5 book - Part 5 of 31Mahmoud Samir Fayed
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
The Ring programming language version 1.3 book - Part 18 of 88
The Ring programming language version 1.3 book - Part 18 of 88The Ring programming language version 1.3 book - Part 18 of 88
The Ring programming language version 1.3 book - Part 18 of 88Mahmoud Samir Fayed
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notesRajiv Gupta
 
The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88Mahmoud Samir Fayed
 
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonByterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonakaptur
 
The Ring programming language version 1.4 book - Part 7 of 30
The Ring programming language version 1.4 book - Part 7 of 30The Ring programming language version 1.4 book - Part 7 of 30
The Ring programming language version 1.4 book - Part 7 of 30Mahmoud Samir Fayed
 
Functional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonFunctional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonCarlos V.
 
Ansible for Beginners
Ansible for BeginnersAnsible for Beginners
Ansible for BeginnersArie Bregman
 
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
Task4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docxTask4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docx
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docxjosies1
 
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...Yashpatel821746
 
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Yashpatel821746
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...Yashpatel821746
 

Similar to Talk Code (20)

Cc code cards
Cc code cardsCc code cards
Cc code cards
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
 
The Ring programming language version 1.5 book - Part 5 of 31
The Ring programming language version 1.5 book - Part 5 of 31The Ring programming language version 1.5 book - Part 5 of 31
The Ring programming language version 1.5 book - Part 5 of 31
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
The Ring programming language version 1.3 book - Part 18 of 88
The Ring programming language version 1.3 book - Part 18 of 88The Ring programming language version 1.3 book - Part 18 of 88
The Ring programming language version 1.3 book - Part 18 of 88
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notes
 
Calvix python
Calvix pythonCalvix python
Calvix python
 
The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189
 
Functional python
Functional pythonFunctional python
Functional python
 
The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88
 
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonByterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
 
The Ring programming language version 1.4 book - Part 7 of 30
The Ring programming language version 1.4 book - Part 7 of 30The Ring programming language version 1.4 book - Part 7 of 30
The Ring programming language version 1.4 book - Part 7 of 30
 
Boosting Developer Productivity with Clang
Boosting Developer Productivity with ClangBoosting Developer Productivity with Clang
Boosting Developer Productivity with Clang
 
Functional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonFunctional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with Python
 
Ansible for Beginners
Ansible for BeginnersAnsible for Beginners
Ansible for Beginners
 
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
Task4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docxTask4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docx
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
 
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
 
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
 

Recently uploaded

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 

Recently uploaded (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 

Talk Code

  • 1. 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 you need 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)
  • 2. 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 ....: ....: 1 2 3 4 5 In [11]: x = 5 In [12]: while x < 100: ....: print x ....: x = x * 2 ....: ....: 5 10 20 40 80 Slide 8 -------------- Conditionals -------------- *If: elif: else:* * if condition: [block] else: [block]
  • 3. --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 statement Write 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.
  • 4. 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 other functions, 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)
  • 5. 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 just sum([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)))
  • 6. 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 as for line in open_file.readlines(): print line#Or whatvere or string = 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 python from 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 *
  • 7. * 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 more http://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 you need them. * import this --Hidden-- Explain. * Slide 20 * --------------- * Decorators *
  • 8. Syntacting sugar for foo_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_deco def 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
  • 9. ---------- *If we have time* * PIL - Image Manipulation * Mechanize - Browser automation * Beautiful Soup - Html extraction. Slide 23 ------------- * Resources * python.org diveintopython.org uswaretech.com/blog Slide 24 ---------- * Thank You. * You can give feedback, ask questions at shabda@uswaretech.com