SlideShare a Scribd company logo
1 of 61
Download to read offline
Intro to Python
   by Daniel Greenfeld
Intro to Python
                 a.k.a.
21 cool things you can do with Python
Tons of content
ā€¢ Please hold your questions until the end
ā€¢ Latest slides will be made available
ā€¢ Special thanks to:
   ā€¢ Raymond Hettinger
   ā€¢ David Beazley
   ā€¢ Audrey Roy
   ā€¢ The Python community
Daniel Greenfeld
                                       ā€¢ pydanny
                                       ā€¢ twitter.com/pydanny
                                       ā€¢ github.com/pydanny
                                       ā€¢ pydanny.blogspot.com
                                       ā€¢ pydanny-event-notes.rtfd.org
   IMG goes here


http://www.ļ¬‚ickr.com/photos/pydanny/4442245488/
Daniel Greenfeld
                    ā€¢ Python/Django Developer
                    ā€¢ Cartwheel Web
                      ā€¢ Makers of
                      ā€¢ Makers of Open Comparison
                    ā€¢ Los Angeles
   IMG goes here    ā€¢ Capoeira
                    ā€¢ Fiancee is Audrey Roy
http://www.ļ¬‚ickr.com/photos/pydanny/4442245488/
Intro to Python
Who uses Python?
    All the cool kids do!
Who uses Python?
What is Python?
What is Python?
ā€¢ Over 20 years old
ā€¢ Dynamic, strongly typed scripting language
ā€¢ Multi-paradigm programming language
 ā€¢ Object Oriented
 ā€¢ Functional
 ā€¢ Procedural
 ā€¢ Reļ¬‚ective
What is Python?
ā€¢ Free and open source
ā€¢ Fast enough
 ā€¢ Check out PyPy
ā€¢ Batteries included language
What is Python?




       http://en.wikipedia.org/wiki/File:Flyingcircus_2.jpg




Itā€™s named after Monty Python
Python is similar to...
ā€¢ Perl
ā€¢ Ruby
ā€¢ Lisp
ā€¢ Java
Python is different than...
ā€¢ Perl
ā€¢ Ruby
ā€¢ Lisp
ā€¢ Java
Python Core Concepts
Whitespace!
""" whitespace.py """
from random import randrange

def numberizer():
    # Generate a random number from 1 to 10.
    return randrange(1, 11)

number = numberizer()
if number > 5:
    print("This number is big!")

class RandomNumberHolder(object):
    # Create and hold 20 random numbers using numberizer

    def __init__(self):
        self.numbers = [numberizer(x) for x in range(20)]

random_numbers = RandomNumberHolder()
Whitespace!


def numberizer():
    # Generate a random number from 1 to 10.
    return randrange(1, 11)
Whitespace!


number = numberizer()
if number > 5:
    print("This number is big!")
Whitespace!

class RandomNumberHolder(object):
    # Create and hold 20 random numbers
        # using numberizer

   def __init__(self):

       self.numbers = [numberizer(x) for x...

random_numbers = RandomNumberHolder()
Philosophy of
        Core Developers
ā€¢ Conservative growth
ā€¢ Aim for a simple implementation
ā€¢ ā€œWe read Knuth so you donā€™t have toā€
Zen of Python
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Culture of Documentation
ā€¢ Django Web Framework
 ā€¢ http://djangoproject.com
ā€¢ Document everything and document well
ā€¢ Make your documentation accessible
 ā€¢ http://readthedocs.org
 ā€¢ http://python-requests.org
 ā€¢ http://bit.ly/oc_ref (Open Comparison reference)
Which Python?
For learning and simple scripting...

Use what is on your
 system by default.
    If you are running Linux or
   BSD you already have Python
$
$ python
Python 2.7.1+ (r271:86832, Apr 11 2011,
18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or
"license" for more information.
>>>
>>> 3 + 4
7
>>> a = 5 * 10
>>> a
50
>>> def add(a, b):
...     return a + b
...
>>> add(3,4)
7
>>> add('Py','thon')
'Python'
Donā€™t have Python yet?


   Download 3.2
Unless you are working with a tool
with a speciļ¬c Python dependency
 (e.g. Django requires Python 2.7)
21 cool things you
can do with Python
#1 Run it anywhere
  Linux                  Windows
FreeBSD                  Mac OS X                         JVM
OpenBSD                   Solaris                        .NET
NetBSD                    HP-UX                        Android OS
  BSD                      OS/2
     http://en.wikipedia.org/wiki/CPython#Supported_platforms
#2 Learn it fast
     Python is easy to learn but powerful.

Experienced developers get up to speed in days.

Lots of tutorials in the area taught by PyLadies.

      http://learnpythonthehardway.org/
#3 Introspect
                a.k.a Introducing the String type
>>> foo = 'bar'
>>> spam = 'eggs'
>>> fun = 'spam and EGGS   '
                                   dir() is a Python built-in function
>>> dir(fun)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__',
'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__',
                                http://en.wikipedia.org/wiki/File:Flyingcircus_2.jpg
'__rmul__', '__setattr__', '__sizeof__', '__str__','__subclasshook__',
'_formatter_field_name_split', '_formatter_parser', 'capitalize',
'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs',
 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower',
'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition',
'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper','zfill']
#3 Introspect
                 a.k.a Introducing the String type
>>> fun
'spam and EGGS     '
>>> fun.strip()
'spam and EGGS'               type() returns the type of object
>>> spam.title()
'Spam And Eggs   '
>>> fun.capitalize()
'Spam and eggs   '
>>> fun.index('a')       Line comments start with ā€˜# ā€˜
2
>>> type(fun)
<type 'str'>
>>> len(fun) # built-in that gives length of object
16
>>> fun[0:5] # String slicing             help() is a
'spam '
>>> help(fun)                           Python built-in
no Python documentation found for 'spam and EGGS      '
>>> help(str)
                                     str is the Python
                                     string type object
#3 Introspect
                a.k.a Introducing the String type
>>> help(str)
Help on class str in module __builtin__:

class str(basestring)
 | str(object) -> string
 |
 | Return a nice string representation of the object.
 | If the argument is a string, the return value is the same object.
 |
 | Method resolution order:
 |      str
 |      basestring
 |      object
 |
 | Methods defined here:
 |
 | __add__(...)
 |      x.__add__(y) <==> x+y
 |
 | __contains__(...)
 |      x.__contains__(y) <==> y in x
#3 Introspect
                a.k.a Introducing the String type
>>> help(str)
| capitalize(...)
|      S.capitalize() -> string
|
|      Return a copy of the string S with only its first character
|      capitalized.
|
| center(...)
|      S.center(width[, fillchar]) -> string
|
|      Return S centered in a string of length width. Padding is
|      done using the specified fill character (default is a space)
|
| count(...)
|      S.count(sub[, start[, end]]) -> int
|
|      Return the number of non-overlapping occurrences of substring sub
in
|      string S[start:end]. Optional arguments start and end are
interpreted
|      as in slice notation.
#4 Things with Strings
>>> scale = 'Southern California Linux Expo'
>>> scale[0]
'S'
>>> scale[0:8]
'Southern'
>>> scale[:-5]
'Southern California Linux'
                                        Strings are immutable
>>> scale[0:8] = 'Northern'
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> scale.replace('Southern California','SoCal')
'SoCal Linux Expo'
>>> scale
'Southern California Linux Expo'
>>> scale = scale.replace('Southern California','SoCal')
>>> scale
'SoCal Linux Expo'
>>> scale.startswith('Windows')
False
>>> scale.endswith('Windows')
False
>>> scale.startswith('SoCal')
True
>>> 'Windows' in scale
False
>>> 'Linux' in scale
True
#5 String formatting
>>> a = "Daniel"
>>> b = "Adam"
>>> c = "Greenfeld"
>>> a + b + c
'DanielAdamGreenfeld'
>>> "{0} {1} {2}".format(a, b, c)
'Daniel Adam Greenfeld'
>>> "{first} {middle} {last}".format(first=a, middle=b, last=c)
'Daniel Adam Greenfeld'
>>> lst = [a,b,c]
>>> lst
['Daniel', 'Adam', 'Greenfeld']
>>> name =" ".join(lst)
>>> name
'Daniel Adam Greenfeld'
#6 Basic Operations
>>> x, y, z = 5, 10, 15
>>> 5 < 10
True
>>> 5 > 10
False
                             Python has advanced math
>>> True == False             features that comes with
False
>>> (5 == x) or (10 == x)        the standard library.
True
>>> (5 == x) and (10 == x)
False
>>> x + y - z
0
>>> 10 * 5                      For scientiļ¬c needs,
50
>>> 10 / 5                      numpy is available.
2
>>> 10 + 5
15
>>> 10 ** 2
100
#7 Lists
>>> my_list = [1, 2, 3]
>>> my_list.append(4)
>>> my_list                           Lists are mutable
[1, 2, 3, 4]
>>> my_list.insert(2, 'dog')
>>> my_list
                                    Tuples are not mutable
[1, 2, 'dog', 3, 4]
>>> my_list.extend([5, 6])
>>> my_list
[1, 2, 'dog', 3, 4, 5, 6]
>>> my_list.append([7, 8])
>>> my_list
[1, 2, 'dog', 3, 4, 5, 6, [7, 8]]
>>> my_list.pop(2)
'dog'
>>> my_list
[1, 2, 3, 4, 5, 6, [7, 8]]
>>> my_list.reverse()
>>> my_list
[[7, 8], 6, 5, 4, 3, 2, 1]
#8 Lists + Functional Programming
>>>   def divisible_by_2(x):
...      return x % 2 == 0
...
>>>                                     Filter constructs a list from
>>>   def cube(x):
...      return x ** 3
                                       those elements of an iterable
...                                   for which the speciļ¬ed function
>>>
>>>   numbers = [1, 2, 3, 4, 6, 31]
                                                returns True.
>>>
>>>   filter(divisible_by_2, numbers)
[2,   4, 6]
>>>
>>>   map(cube, numbers)
[1,   8, 27, 64, 216, 29791]         Map applies the speciļ¬ed
                                   function to every item of the
                                 iterable and returns the results.
#9 List Comprehensions
                            Remember
""" whitespace.py """
from random import randrange                         this
def numberizer():                                 from the
    # Generate a random number from 1 to 10.
    return randrange(1, 11)
                                                 beginning?
number = numberizer()
if number > 5:
              List Comprehension!
    print("This number is big!")

class RandomNumberHolder(object):
    # Create and hold 20 random numbers using numberizer

    def __init__(self):
        self.numbers = [numberizer(x) for x in range(20)]

random_numbers = RandomNumberHolder()
#9 List Comprehensions
>>>   items = [x for x in range(20)]
>>>   items
[0,   1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>>   [x for x in range(20) if x % 2]
[1,   3, 5, 7, 9, 11, 13, 15, 17, 19]


                    List Comprehensions are
                   wonderful syntactical sugar.
>>> # Fizzbuzz solved using Python's List Comprehension
>>> lst = [(x, 'Fizz', 'Buzz', 'FizzBuzz') 
...            [(not x % 3) | (not x % 5) << 1] for x in range(20)]

                                        Backslash can be used to
                                        break up long statements.
                                           Please use sparingly!
#10 Generators
>>> def countdown(n):
...     print("Counting down from {0}".format(n))
...     while n > 0:
...        yield n             A generator evaluates only when the
...        n -= 1              iterable is at that iteration. This is really
                               powerful, especially when working with
>>> x = countdown(10)          large iterables.
>>> x
<generator object at 0x58490>
>>> x.next()
Counting down from 10
10                                       A billion iterations for
>>> x.next()
9                                      a generator is NOTHING.
>>> x.next()
8
>>> x.next()
7

                      http://dabeaz.com/generators/Generators.pdf
#11 Generator Expressions
>>> items = (str(x) for x in xrange(10000))         Generator expressions are
>>> items
<generator object <genexpr> at 0x100721460>         shorthand for generators. Just
                                                    like list comprehensions, but
                                                    with () instead of [].




                    http://dabeaz.com/generators/Generators.pdf
#11 Generator Expressions
Problem: count the bytes saved to huge apache access log.
wwwlog = open("access-log")
total = 0                                    Open the whole ļ¬le, then
for line in wwwlog:
    bytestr = line.rsplit(None,1)[1]        iterate through the results.
    if bytestr != '-':
        total += int(bytestr)
                                              Lots of memory usage!
print "Total", total


            # generator expressions way
Generator   wwwlog     = open("access-log")
            bytecolumn = (line.rsplit(None,1)[1] for line in wwwlog)
  way       bytes      = (int(x) for x in bytecolumn if x != '-')
            print "Total", sum(bytes)

                  http://dabeaz.com/generators/Generators.pdf
#12 Sets
>>> lst = [1,1,1,1,1,2,2,2,3,3,3,3,3,3]
>>> s = set(lst)
>>> s
set([1,2,3])

  Counting unique words in the Gettysburg Address
>>>   address = """Four score and seven years ago our fathers brought..."""
>>>   for r in [',','.','-']:
...       address = address.replace(r,'')
>>>
>>>
      words = address.split(' ')
      len(words)
                                        All items in a set need to
278
>>>   unique_words = set(words)
                                          be of the same type.
>>>   len(unique_words)
143
>>> data = {                       #13 Dictionaries
       'name':'Daniel Greenfeld',
       'nickname':'pydanny',
       'states_lived':['CA','KS','MD','NJ','VA','AD'],
       'fiancee':'Audrey Roy'
       }
>>> data['name']
'Daniel Greenfeld'
>>> data['nickname'] = 'audreyr'       Mutable Key/Value objects
>>> data['nickname']
'audreyr'
>>> data['nickname'] = 'pydanny'
>>> data.keys()
['fiancee', 'nickname', 'name', 'states_lived']
>>> data.get('fiancee')
'Audrey Roy'
>>> data.get('fiance')
None
>>> data.pop('fiancee')
'Audrey Roy'
>>> data
{'nickname': 'pydanny', 'name': 'Daniel Greenfeld', 'states_lived': ['CA',
'KS', 'MD', 'NJ', 'VA']}
>>> data['fiancee'] = 'Audrey Roy'
>>> data
{'fiancee': 'Audrey Roy', 'nickname': 'pydanny', 'name': 'Daniel
Greenfeld', 'states_lived': ['CA', 'KS', 'MD', 'NJ', 'VA', 'AD']}
#14 Object-Oriented Programming
class Animal(object):
    def __init__(self, name):
        self.name = name
    def talk(self):
        raise NotImplementedError("Subclass must implement abstract method")

class Cat(Animal):
    def talk(self):
        return 'Meow!'

class Dog(Animal):                                       Missy: Meow!
    def talk(self):
        return 'Woof! Woof!'                             Mr. Mistoffelees: Meow!
animals = [Cat('Missy'),                                 Lassie: Woof! Woof!
           Cat('Mr. Mistoffelees'),
           Dog('Lassie')]

for animal in animals:
    print animal.name + ': ' + animal.talk()


                      Barely scratching the surface!
           http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming#Examples
#15 Isolate Environments
$ curl http://bit.ly/get-pip | python
$ pip install virtualenv
$ virtualenv my_env
$ source my_env/bin/activate
(my_env) $
           Pro Tip: easy_install is legacy. Use pip.
(my_env) $ pip install django==1.3.1
(my_env) $ pip install requests==0.9.1
(my_env) $ pip install mongoengine==0.5.2
                                                     Warning!
(my_env) $ pip install celery==2.4.6               Only installs
(my_env) $ pip freeze
celery==2.4.6                                     Python drivers!
django==1.3.1
mongoengine==0.5.2                                Not MongoDB
requests==0.9.1
(my_env) $ pip freeze > requirements.txt           or RabbitMQ
...
(another_env) $ pip install -r requirements.txt
#16 Colorize Code
                How Github and Bitbucket do it
$ pip install pygments
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter

if __name__ == '__main__':
    # get this file
                                                    pygments_demo.py
    code = open("pygments_demo.py", "rw").read()

   # figure out the lexer
   lexer = get_lexer_by_name("python", stripall=True)

   # construct the formatter
   formatter = HtmlFormatter(linenos=False, cssclass="source")

   # style and formatting
   css = HtmlFormatter().get_style_defs('.source')
   highlighted_code = highlight(code, lexer, formatter)
   page = """
                             $ python pygments_demo.py > text.html
       <html>
           <head><style>{css}</style></head>
           <body>{highlighted_code}</body>
       </html>
       """.format(css=css, highlighted_code=highlighted_code)
   print(page)
Output of the program

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter       text.html
if __name__ == '__main__':
    # get this file
    code = open("pygments_demo.py", "rw").read()

   # figure out the lexer
   lexer = get_lexer_by_name("python", stripall=True)

   # construct the formatter
   formatter = HtmlFormatter(linenos=False, cssclass="source")

   # style and formatting
   css = HtmlFormatter().get_style_defs('.source')
   highlighted_code = highlight(code, lexer, formatter)
   page = """
       <html>
           <head><style>{css}</style></head>
           <body>{highlighted_code}</body>
       </html>
       """.format(css=css, highlighted_code=highlighted_code)
   print(page)
#17 Work with Relational Databases
(my_env)$ pip install django
 from datetime import datetime           Internationalization!
 from django.contrib.auth.models import User
 from django.db import models
 from django.utils.translation import ugettext_lazy as _

 class Post(models.Model):

     author = models.ForeignKey(User)
     title = models.CharField(_('Title'), max_length=100)
     content = models.TextField(_("Content"))
     pub_date = models.DateTimeField(_("Publication date"))

 class Comment(models.Model):
     post = models.ForeignKey(Post)
     name = models.CharField(_('Title'), max_length=100)
     content = models.TextField(_("Content"))
#18 Work with NoSQL
(my_env)$ pip install pymongo
>>> import pymongo
>>> connection = pymongo.Connection("localhost", 27017)
>>> db = connection.test
>>> db.name
u'test'
>>> db.my_collection
Collection(Database(Connection('localhost', 27017), u'test'),
u'my_collection')
>>> db.my_collection.save({"x": 10})
ObjectId('4aba15ebe23f6b53b0000000')
>>> db.my_collection.save({"x": 8})
ObjectId('4aba160ee23f6b543e000000')
>>> db.my_collection.save({"x": 11})
ObjectId('4aba160ee23f6b543e000002')
>>> db.my_collection.find_one()
{u'x': 10, u'_id': ObjectId('4aba15ebe23f6b53b0000000')}
>>> db.my_collection.create_index("x")
u'x_1'
>>> [item["x"] for item in db.my_collection.find().limit(2).skip(1)]
[8, 11]
#19 Message Queues
(my_env)$ pip install celery==2.4.6
(my_env)$ pip install requests==0.9.2
   import logging                                 products/tasks.py
   import requests
   from celery import task

   from products.models import Product
                                                  Decorators wrap a
   logger = logging.getLogger('products.tasks')
                                                  function or method
   @task
   def check_all_images():
                                                    with a function.
       for product in Product.objects.all():
           response = request.get(product.medium_image.url)
           if response.status_code != 200:
               msg = "Product {0} missing image".format(product.id)
               logging.warning(msg)
   >>> from products.tasks import confirm_all_images
   >>> result = confirm_all_images.delay()
   >>> result.ready()
   False
   >>> result.ready()
   True
#20 Work with JSON
>>> import json
>>> data = {
    'name':'Daniel Greenfeld',
    'nickname':'pydanny',
    'states_lived':['CA','KS','MD','NJ','VA','AD'],
    'fiancee':'Audrey Roy'
    }
>>> type(data)
<type 'dict'>
>>> payload = json.dumps(data)
>>> payload
'{"fiancee": "Audrey Roy", "nickname": "pydanny", "name": "Daniel
Greenfeld", "states_lived": ["CA", "KS", "MD", "NJ", "VA", "AD"]}'
>>> type(payload)
<type 'str'>
>>> restored = json.loads(payload)
>>> type(restored)
<type 'dict'>
>>> restored
{u'fiancee': u'Audrey Roy', u'nickname': u'pydanny', u'name': u'Daniel
Greenfeld', u'states_lived': [u'CA', u'KS', u'MD', u'NJ', u'VA', u'AD'
]}
#21 Serve the Web
 $ pip install ļ¬‚ask==0.8
  # webapp.py
  from flask import Flask
  app = Flask(__name__)

  @app.route("/")
  def hello():
      return "Hello World!"

  if __name__ == "__main__":
      app.run()


      ļ¬‚ask.pocoo.org
#21 Serve the Web




 Lots more frameworks!
#21 Serve the Web




  http://science.nasa.gov/
#21 Serve the Web




http://djangopackages.com
http://opencomparison.org
#21 Serve the Web




http://consumernotebook.com
#21 Serve the Web




    http://grove.io

     Hosted IRC
Finis
ā€¢ Learn more at the following booths:
 ā€¢ Python
 ā€¢ Django
 ā€¢ Pyladies
Questions?

More Related Content

What's hot

Full Python in 20 slides
Full Python in 20 slidesFull Python in 20 slides
Full Python in 20 slides
rfojdar
Ā 

What's hot (20)

The FatRat
The FatRatThe FatRat
The FatRat
Ā 
Python pandas tutorial
Python pandas tutorialPython pandas tutorial
Python pandas tutorial
Ā 
Python programming
Python  programmingPython  programming
Python programming
Ā 
An Introduction to Python Programming
An Introduction to Python ProgrammingAn Introduction to Python Programming
An Introduction to Python Programming
Ā 
Python programming : Threads
Python programming : ThreadsPython programming : Threads
Python programming : Threads
Ā 
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Ā 
Python Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaPython Collections Tutorial | Edureka
Python Collections Tutorial | Edureka
Ā 
How to Prevent RFI and LFI Attacks
How to Prevent RFI and LFI AttacksHow to Prevent RFI and LFI Attacks
How to Prevent RFI and LFI Attacks
Ā 
CEH - Module 10 : Denial of Service
CEH - Module 10 : Denial of ServiceCEH - Module 10 : Denial of Service
CEH - Module 10 : Denial of Service
Ā 
2022 APIsecure_Method for exploiting IDOR on nodejs+mongodb based backend
2022 APIsecure_Method for exploiting IDOR on nodejs+mongodb based backend2022 APIsecure_Method for exploiting IDOR on nodejs+mongodb based backend
2022 APIsecure_Method for exploiting IDOR on nodejs+mongodb based backend
Ā 
python ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institutepython ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institute
Ā 
Full Python in 20 slides
Full Python in 20 slidesFull Python in 20 slides
Full Python in 20 slides
Ā 
AlphaGo: Mastering the Game of Go with Deep Neural Networks and Tree Search
AlphaGo: Mastering the Game of Go with Deep Neural Networks and Tree SearchAlphaGo: Mastering the Game of Go with Deep Neural Networks and Tree Search
AlphaGo: Mastering the Game of Go with Deep Neural Networks and Tree Search
Ā 
Malware Analysis Made Simple
Malware Analysis Made SimpleMalware Analysis Made Simple
Malware Analysis Made Simple
Ā 
Rails Best Practices
Rails Best PracticesRails Best Practices
Rails Best Practices
Ā 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
Ā 
Plotting data with python and pylab
Plotting data with python and pylabPlotting data with python and pylab
Plotting data with python and pylab
Ā 
Learn python ā€“ for beginners
Learn python ā€“ for beginnersLearn python ā€“ for beginners
Learn python ā€“ for beginners
Ā 
Python tools to deploy your machine learning models faster
Python tools to deploy your machine learning models fasterPython tools to deploy your machine learning models faster
Python tools to deploy your machine learning models faster
Ā 
Introduction To Python
Introduction To PythonIntroduction To Python
Introduction To Python
Ā 

Viewers also liked

Python
Python Python
Python
Edureka!
Ā 
Samarjit Kachari-New media:Hope for literature and language survival?
Samarjit Kachari-New media:Hope for literature and language survival?Samarjit Kachari-New media:Hope for literature and language survival?
Samarjit Kachari-New media:Hope for literature and language survival?
pumediaseminar2011
Ā 

Viewers also liked (20)

Intro to Python Workshop San Diego, CA (January 19, 2013)
Intro to Python Workshop San Diego, CA (January 19, 2013)Intro to Python Workshop San Diego, CA (January 19, 2013)
Intro to Python Workshop San Diego, CA (January 19, 2013)
Ā 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
Ā 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
Ā 
Welcome to Python
Welcome to PythonWelcome to Python
Welcome to Python
Ā 
Health 2.0 pre ga slides day 1 & change management
Health 2.0 pre ga slides day 1 & change managementHealth 2.0 pre ga slides day 1 & change management
Health 2.0 pre ga slides day 1 & change management
Ā 
Ctrc python
Ctrc pythonCtrc python
Ctrc python
Ā 
Python
Python Python
Python
Ā 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
Ā 
Samarjit Kachari-New media:Hope for literature and language survival?
Samarjit Kachari-New media:Hope for literature and language survival?Samarjit Kachari-New media:Hope for literature and language survival?
Samarjit Kachari-New media:Hope for literature and language survival?
Ā 
Why Python?
Why Python?Why Python?
Why Python?
Ā 
Intro
IntroIntro
Intro
Ā 
Intro to Data Visualizations
Intro to Data VisualizationsIntro to Data Visualizations
Intro to Data Visualizations
Ā 
PyCon Philippines 2012 Keynote
PyCon Philippines 2012 KeynotePyCon Philippines 2012 Keynote
PyCon Philippines 2012 Keynote
Ā 
The One Way
The One WayThe One Way
The One Way
Ā 
Python: The Programmer's Lingua Franca
Python: The Programmer's Lingua FrancaPython: The Programmer's Lingua Franca
Python: The Programmer's Lingua Franca
Ā 
Lighting talk on django-social-auth
Lighting talk on django-social-authLighting talk on django-social-auth
Lighting talk on django-social-auth
Ā 
Rapid Prototyping with Python
Rapid Prototyping with PythonRapid Prototyping with Python
Rapid Prototyping with Python
Ā 
Introduction to Scratch Programming
Introduction to Scratch ProgrammingIntroduction to Scratch Programming
Introduction to Scratch Programming
Ā 
Esri South Africa Python for Everyone
Esri South Africa Python for EveryoneEsri South Africa Python for Everyone
Esri South Africa Python for Everyone
Ā 
From Prospect To Production In 30 Days
From Prospect To Production In 30 DaysFrom Prospect To Production In 30 Days
From Prospect To Production In 30 Days
Ā 

Similar to Intro to Python

Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
niklal
Ā 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
Chui-Wen Chiu
Ā 
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
Ā 
PPT on Python - illustrating Python for BBA, B.Tech
PPT on Python - illustrating Python for BBA, B.TechPPT on Python - illustrating Python for BBA, B.Tech
PPT on Python - illustrating Python for BBA, B.Tech
ssuser2678ab
Ā 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
Simplilearn
Ā 
Migrating from matlab to python
Migrating from matlab to pythonMigrating from matlab to python
Migrating from matlab to python
ActiveState
Ā 
Python bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of NairobiPython bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of Nairobi
krmboya
Ā 
Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)
Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)
Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)
Takayuki Shimizukawa
Ā 

Similar to Intro to Python (20)

Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
Ā 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
Ā 
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...
Ā 
PPT on Python - illustrating Python for BBA, B.Tech
PPT on Python - illustrating Python for BBA, B.TechPPT on Python - illustrating Python for BBA, B.Tech
PPT on Python - illustrating Python for BBA, B.Tech
Ā 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
Ā 
Overview of Python - Bsides Detroit 2012
Overview of Python - Bsides Detroit 2012Overview of Python - Bsides Detroit 2012
Overview of Python - Bsides Detroit 2012
Ā 
Python Tutorial
Python TutorialPython Tutorial
Python Tutorial
Ā 
PythonäŗŽWeb 2.0ē½‘ē«™ēš„åŗ”ē”Ø - QCon Beijing 2010
PythonäŗŽWeb 2.0ē½‘ē«™ēš„åŗ”ē”Ø - QCon Beijing 2010PythonäŗŽWeb 2.0ē½‘ē«™ēš„åŗ”ē”Ø - QCon Beijing 2010
PythonäŗŽWeb 2.0ē½‘ē«™ēš„åŗ”ē”Ø - QCon Beijing 2010
Ā 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
Ā 
Python in 90 minutes
Python in 90 minutesPython in 90 minutes
Python in 90 minutes
Ā 
Learn Python 3 for absolute beginners
Learn Python 3 for absolute beginnersLearn Python 3 for absolute beginners
Learn Python 3 for absolute beginners
Ā 
Python in 30 minutes!
Python in 30 minutes!Python in 30 minutes!
Python in 30 minutes!
Ā 
Becoming a Pythonist
Becoming a PythonistBecoming a Pythonist
Becoming a Pythonist
Ā 
Python ppt
Python pptPython ppt
Python ppt
Ā 
Sphinx autodoc - automated api documentation - PyCon.KR 2015
Sphinx autodoc - automated api documentation - PyCon.KR 2015Sphinx autodoc - automated api documentation - PyCon.KR 2015
Sphinx autodoc - automated api documentation - PyCon.KR 2015
Ā 
Migrating from matlab to python
Migrating from matlab to pythonMigrating from matlab to python
Migrating from matlab to python
Ā 
Python bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of NairobiPython bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of Nairobi
Ā 
01-Python-Basics.ppt
01-Python-Basics.ppt01-Python-Basics.ppt
01-Python-Basics.ppt
Ā 
Sphinx autodoc - automated api documentation - PyCon.MY 2015
Sphinx autodoc - automated api documentation - PyCon.MY 2015Sphinx autodoc - automated api documentation - PyCon.MY 2015
Sphinx autodoc - automated api documentation - PyCon.MY 2015
Ā 
Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)
Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)
Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)
Ā 

More from Daniel Greenfeld

From NASA to Startups to Big Commerce
From NASA to Startups to Big CommerceFrom NASA to Startups to Big Commerce
From NASA to Startups to Big Commerce
Daniel Greenfeld
Ā 
How to sell django panel
How to sell django panelHow to sell django panel
How to sell django panel
Daniel Greenfeld
Ā 

More from Daniel Greenfeld (19)

How to Write a Popular Python Library by Accident
How to Write a Popular Python Library by AccidentHow to Write a Popular Python Library by Accident
How to Write a Popular Python Library by Accident
Ā 
10 more-things-you-can-do-with-python
10 more-things-you-can-do-with-python10 more-things-you-can-do-with-python
10 more-things-you-can-do-with-python
Ā 
From NASA to Startups to Big Commerce
From NASA to Startups to Big CommerceFrom NASA to Startups to Big Commerce
From NASA to Startups to Big Commerce
Ā 
Thinking hard about_python
Thinking hard about_pythonThinking hard about_python
Thinking hard about_python
Ā 
An Extreme Talk about the Zen of Python
An Extreme Talk about the Zen of PythonAn Extreme Talk about the Zen of Python
An Extreme Talk about the Zen of Python
Ā 
Round pegs and square holes
Round pegs and square holesRound pegs and square holes
Round pegs and square holes
Ā 
Future of Collaboration
Future of CollaborationFuture of Collaboration
Future of Collaboration
Ā 
Advanced Django Forms Usage
Advanced Django Forms UsageAdvanced Django Forms Usage
Advanced Django Forms Usage
Ā 
Confessions of Joe Developer
Confessions of Joe DeveloperConfessions of Joe Developer
Confessions of Joe Developer
Ā 
Python Worst Practices
Python Worst PracticesPython Worst Practices
Python Worst Practices
Ā 
Django Worst Practices
Django Worst PracticesDjango Worst Practices
Django Worst Practices
Ā 
How to sell django panel
How to sell django panelHow to sell django panel
How to sell django panel
Ā 
Pinax Long Tutorial Slides
Pinax Long Tutorial SlidesPinax Long Tutorial Slides
Pinax Long Tutorial Slides
Ā 
Testing In Django
Testing In DjangoTesting In Django
Testing In Django
Ā 
Django Uni-Form
Django Uni-FormDjango Uni-Form
Django Uni-Form
Ā 
Nova Django
Nova DjangoNova Django
Nova Django
Ā 
Pinax Introduction
Pinax IntroductionPinax Introduction
Pinax Introduction
Ā 
Why Django
Why DjangoWhy Django
Why Django
Ā 
Pinax Tutorial 09/09/09
Pinax Tutorial 09/09/09Pinax Tutorial 09/09/09
Pinax Tutorial 09/09/09
Ā 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(ā˜Žļø+971_581248768%)**%*]'#abortion pills for sale in dubai@
Ā 
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
panagenda
Ā 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
Ā 

Recently uploaded (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
Ā 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Ā 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Ā 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
Ā 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Ā 
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
Ā 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Ā 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
Ā 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
Ā 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Ā 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
Ā 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
Ā 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
Ā 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Ā 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Ā 
Scaling API-first ā€“ The story of a global engineering organization
Scaling API-first ā€“ The story of a global engineering organizationScaling API-first ā€“ The story of a global engineering organization
Scaling API-first ā€“ The story of a global engineering organization
Ā 
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
Ā 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
Ā 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
Ā 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
Ā 

Intro to Python

  • 1. Intro to Python by Daniel Greenfeld
  • 2. Intro to Python a.k.a. 21 cool things you can do with Python
  • 3. Tons of content ā€¢ Please hold your questions until the end ā€¢ Latest slides will be made available ā€¢ Special thanks to: ā€¢ Raymond Hettinger ā€¢ David Beazley ā€¢ Audrey Roy ā€¢ The Python community
  • 4. Daniel Greenfeld ā€¢ pydanny ā€¢ twitter.com/pydanny ā€¢ github.com/pydanny ā€¢ pydanny.blogspot.com ā€¢ pydanny-event-notes.rtfd.org IMG goes here http://www.ļ¬‚ickr.com/photos/pydanny/4442245488/
  • 5. Daniel Greenfeld ā€¢ Python/Django Developer ā€¢ Cartwheel Web ā€¢ Makers of ā€¢ Makers of Open Comparison ā€¢ Los Angeles IMG goes here ā€¢ Capoeira ā€¢ Fiancee is Audrey Roy http://www.ļ¬‚ickr.com/photos/pydanny/4442245488/
  • 7. Who uses Python? All the cool kids do!
  • 10. What is Python? ā€¢ Over 20 years old ā€¢ Dynamic, strongly typed scripting language ā€¢ Multi-paradigm programming language ā€¢ Object Oriented ā€¢ Functional ā€¢ Procedural ā€¢ Reļ¬‚ective
  • 11. What is Python? ā€¢ Free and open source ā€¢ Fast enough ā€¢ Check out PyPy ā€¢ Batteries included language
  • 12. What is Python? http://en.wikipedia.org/wiki/File:Flyingcircus_2.jpg Itā€™s named after Monty Python
  • 13. Python is similar to... ā€¢ Perl ā€¢ Ruby ā€¢ Lisp ā€¢ Java
  • 14. Python is different than... ā€¢ Perl ā€¢ Ruby ā€¢ Lisp ā€¢ Java
  • 16. Whitespace! """ whitespace.py """ from random import randrange def numberizer(): # Generate a random number from 1 to 10. return randrange(1, 11) number = numberizer() if number > 5: print("This number is big!") class RandomNumberHolder(object): # Create and hold 20 random numbers using numberizer def __init__(self): self.numbers = [numberizer(x) for x in range(20)] random_numbers = RandomNumberHolder()
  • 17. Whitespace! def numberizer(): # Generate a random number from 1 to 10. return randrange(1, 11)
  • 18. Whitespace! number = numberizer() if number > 5: print("This number is big!")
  • 19. Whitespace! class RandomNumberHolder(object): # Create and hold 20 random numbers # using numberizer def __init__(self): self.numbers = [numberizer(x) for x... random_numbers = RandomNumberHolder()
  • 20. Philosophy of Core Developers ā€¢ Conservative growth ā€¢ Aim for a simple implementation ā€¢ ā€œWe read Knuth so you donā€™t have toā€
  • 21. Zen of Python >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
  • 22. Culture of Documentation ā€¢ Django Web Framework ā€¢ http://djangoproject.com ā€¢ Document everything and document well ā€¢ Make your documentation accessible ā€¢ http://readthedocs.org ā€¢ http://python-requests.org ā€¢ http://bit.ly/oc_ref (Open Comparison reference)
  • 24. For learning and simple scripting... Use what is on your system by default. If you are running Linux or BSD you already have Python
  • 25. $ $ python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> 3 + 4 7 >>> a = 5 * 10 >>> a 50 >>> def add(a, b): ... return a + b ... >>> add(3,4) 7 >>> add('Py','thon') 'Python'
  • 26. Donā€™t have Python yet? Download 3.2 Unless you are working with a tool with a speciļ¬c Python dependency (e.g. Django requires Python 2.7)
  • 27. 21 cool things you can do with Python
  • 28. #1 Run it anywhere Linux Windows FreeBSD Mac OS X JVM OpenBSD Solaris .NET NetBSD HP-UX Android OS BSD OS/2 http://en.wikipedia.org/wiki/CPython#Supported_platforms
  • 29. #2 Learn it fast Python is easy to learn but powerful. Experienced developers get up to speed in days. Lots of tutorials in the area taught by PyLadies. http://learnpythonthehardway.org/
  • 30. #3 Introspect a.k.a Introducing the String type >>> foo = 'bar' >>> spam = 'eggs' >>> fun = 'spam and EGGS ' dir() is a Python built-in function >>> dir(fun) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', http://en.wikipedia.org/wiki/File:Flyingcircus_2.jpg '__rmul__', '__setattr__', '__sizeof__', '__str__','__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper','zfill']
  • 31. #3 Introspect a.k.a Introducing the String type >>> fun 'spam and EGGS ' >>> fun.strip() 'spam and EGGS' type() returns the type of object >>> spam.title() 'Spam And Eggs ' >>> fun.capitalize() 'Spam and eggs ' >>> fun.index('a') Line comments start with ā€˜# ā€˜ 2 >>> type(fun) <type 'str'> >>> len(fun) # built-in that gives length of object 16 >>> fun[0:5] # String slicing help() is a 'spam ' >>> help(fun) Python built-in no Python documentation found for 'spam and EGGS ' >>> help(str) str is the Python string type object
  • 32. #3 Introspect a.k.a Introducing the String type >>> help(str) Help on class str in module __builtin__: class str(basestring) | str(object) -> string | | Return a nice string representation of the object. | If the argument is a string, the return value is the same object. | | Method resolution order: | str | basestring | object | | Methods defined here: | | __add__(...) | x.__add__(y) <==> x+y | | __contains__(...) | x.__contains__(y) <==> y in x
  • 33. #3 Introspect a.k.a Introducing the String type >>> help(str) | capitalize(...) | S.capitalize() -> string | | Return a copy of the string S with only its first character | capitalized. | | center(...) | S.center(width[, fillchar]) -> string | | Return S centered in a string of length width. Padding is | done using the specified fill character (default is a space) | | count(...) | S.count(sub[, start[, end]]) -> int | | Return the number of non-overlapping occurrences of substring sub in | string S[start:end]. Optional arguments start and end are interpreted | as in slice notation.
  • 34. #4 Things with Strings >>> scale = 'Southern California Linux Expo' >>> scale[0] 'S' >>> scale[0:8] 'Southern' >>> scale[:-5] 'Southern California Linux' Strings are immutable >>> scale[0:8] = 'Northern' Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: 'str' object does not support item assignment >>> scale.replace('Southern California','SoCal') 'SoCal Linux Expo' >>> scale 'Southern California Linux Expo' >>> scale = scale.replace('Southern California','SoCal') >>> scale 'SoCal Linux Expo' >>> scale.startswith('Windows') False >>> scale.endswith('Windows') False >>> scale.startswith('SoCal') True >>> 'Windows' in scale False >>> 'Linux' in scale True
  • 35. #5 String formatting >>> a = "Daniel" >>> b = "Adam" >>> c = "Greenfeld" >>> a + b + c 'DanielAdamGreenfeld' >>> "{0} {1} {2}".format(a, b, c) 'Daniel Adam Greenfeld' >>> "{first} {middle} {last}".format(first=a, middle=b, last=c) 'Daniel Adam Greenfeld' >>> lst = [a,b,c] >>> lst ['Daniel', 'Adam', 'Greenfeld'] >>> name =" ".join(lst) >>> name 'Daniel Adam Greenfeld'
  • 36. #6 Basic Operations >>> x, y, z = 5, 10, 15 >>> 5 < 10 True >>> 5 > 10 False Python has advanced math >>> True == False features that comes with False >>> (5 == x) or (10 == x) the standard library. True >>> (5 == x) and (10 == x) False >>> x + y - z 0 >>> 10 * 5 For scientiļ¬c needs, 50 >>> 10 / 5 numpy is available. 2 >>> 10 + 5 15 >>> 10 ** 2 100
  • 37. #7 Lists >>> my_list = [1, 2, 3] >>> my_list.append(4) >>> my_list Lists are mutable [1, 2, 3, 4] >>> my_list.insert(2, 'dog') >>> my_list Tuples are not mutable [1, 2, 'dog', 3, 4] >>> my_list.extend([5, 6]) >>> my_list [1, 2, 'dog', 3, 4, 5, 6] >>> my_list.append([7, 8]) >>> my_list [1, 2, 'dog', 3, 4, 5, 6, [7, 8]] >>> my_list.pop(2) 'dog' >>> my_list [1, 2, 3, 4, 5, 6, [7, 8]] >>> my_list.reverse() >>> my_list [[7, 8], 6, 5, 4, 3, 2, 1]
  • 38. #8 Lists + Functional Programming >>> def divisible_by_2(x): ... return x % 2 == 0 ... >>> Filter constructs a list from >>> def cube(x): ... return x ** 3 those elements of an iterable ... for which the speciļ¬ed function >>> >>> numbers = [1, 2, 3, 4, 6, 31] returns True. >>> >>> filter(divisible_by_2, numbers) [2, 4, 6] >>> >>> map(cube, numbers) [1, 8, 27, 64, 216, 29791] Map applies the speciļ¬ed function to every item of the iterable and returns the results.
  • 39. #9 List Comprehensions Remember """ whitespace.py """ from random import randrange this def numberizer(): from the # Generate a random number from 1 to 10. return randrange(1, 11) beginning? number = numberizer() if number > 5: List Comprehension! print("This number is big!") class RandomNumberHolder(object): # Create and hold 20 random numbers using numberizer def __init__(self): self.numbers = [numberizer(x) for x in range(20)] random_numbers = RandomNumberHolder()
  • 40. #9 List Comprehensions >>> items = [x for x in range(20)] >>> items [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] >>> [x for x in range(20) if x % 2] [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] List Comprehensions are wonderful syntactical sugar. >>> # Fizzbuzz solved using Python's List Comprehension >>> lst = [(x, 'Fizz', 'Buzz', 'FizzBuzz') ... [(not x % 3) | (not x % 5) << 1] for x in range(20)] Backslash can be used to break up long statements. Please use sparingly!
  • 41. #10 Generators >>> def countdown(n): ... print("Counting down from {0}".format(n)) ... while n > 0: ... yield n A generator evaluates only when the ... n -= 1 iterable is at that iteration. This is really powerful, especially when working with >>> x = countdown(10) large iterables. >>> x <generator object at 0x58490> >>> x.next() Counting down from 10 10 A billion iterations for >>> x.next() 9 a generator is NOTHING. >>> x.next() 8 >>> x.next() 7 http://dabeaz.com/generators/Generators.pdf
  • 42. #11 Generator Expressions >>> items = (str(x) for x in xrange(10000)) Generator expressions are >>> items <generator object <genexpr> at 0x100721460> shorthand for generators. Just like list comprehensions, but with () instead of []. http://dabeaz.com/generators/Generators.pdf
  • 43. #11 Generator Expressions Problem: count the bytes saved to huge apache access log. wwwlog = open("access-log") total = 0 Open the whole ļ¬le, then for line in wwwlog: bytestr = line.rsplit(None,1)[1] iterate through the results. if bytestr != '-': total += int(bytestr) Lots of memory usage! print "Total", total # generator expressions way Generator wwwlog = open("access-log") bytecolumn = (line.rsplit(None,1)[1] for line in wwwlog) way bytes = (int(x) for x in bytecolumn if x != '-') print "Total", sum(bytes) http://dabeaz.com/generators/Generators.pdf
  • 44. #12 Sets >>> lst = [1,1,1,1,1,2,2,2,3,3,3,3,3,3] >>> s = set(lst) >>> s set([1,2,3]) Counting unique words in the Gettysburg Address >>> address = """Four score and seven years ago our fathers brought...""" >>> for r in [',','.','-']: ... address = address.replace(r,'') >>> >>> words = address.split(' ') len(words) All items in a set need to 278 >>> unique_words = set(words) be of the same type. >>> len(unique_words) 143
  • 45. >>> data = { #13 Dictionaries 'name':'Daniel Greenfeld', 'nickname':'pydanny', 'states_lived':['CA','KS','MD','NJ','VA','AD'], 'fiancee':'Audrey Roy' } >>> data['name'] 'Daniel Greenfeld' >>> data['nickname'] = 'audreyr' Mutable Key/Value objects >>> data['nickname'] 'audreyr' >>> data['nickname'] = 'pydanny' >>> data.keys() ['fiancee', 'nickname', 'name', 'states_lived'] >>> data.get('fiancee') 'Audrey Roy' >>> data.get('fiance') None >>> data.pop('fiancee') 'Audrey Roy' >>> data {'nickname': 'pydanny', 'name': 'Daniel Greenfeld', 'states_lived': ['CA', 'KS', 'MD', 'NJ', 'VA']} >>> data['fiancee'] = 'Audrey Roy' >>> data {'fiancee': 'Audrey Roy', 'nickname': 'pydanny', 'name': 'Daniel Greenfeld', 'states_lived': ['CA', 'KS', 'MD', 'NJ', 'VA', 'AD']}
  • 46. #14 Object-Oriented Programming class Animal(object): def __init__(self, name): self.name = name def talk(self): raise NotImplementedError("Subclass must implement abstract method") class Cat(Animal): def talk(self): return 'Meow!' class Dog(Animal): Missy: Meow! def talk(self): return 'Woof! Woof!' Mr. Mistoffelees: Meow! animals = [Cat('Missy'), Lassie: Woof! Woof! Cat('Mr. Mistoffelees'), Dog('Lassie')] for animal in animals: print animal.name + ': ' + animal.talk() Barely scratching the surface! http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming#Examples
  • 47. #15 Isolate Environments $ curl http://bit.ly/get-pip | python $ pip install virtualenv $ virtualenv my_env $ source my_env/bin/activate (my_env) $ Pro Tip: easy_install is legacy. Use pip. (my_env) $ pip install django==1.3.1 (my_env) $ pip install requests==0.9.1 (my_env) $ pip install mongoengine==0.5.2 Warning! (my_env) $ pip install celery==2.4.6 Only installs (my_env) $ pip freeze celery==2.4.6 Python drivers! django==1.3.1 mongoengine==0.5.2 Not MongoDB requests==0.9.1 (my_env) $ pip freeze > requirements.txt or RabbitMQ ... (another_env) $ pip install -r requirements.txt
  • 48. #16 Colorize Code How Github and Bitbucket do it $ pip install pygments from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import HtmlFormatter if __name__ == '__main__': # get this file pygments_demo.py code = open("pygments_demo.py", "rw").read() # figure out the lexer lexer = get_lexer_by_name("python", stripall=True) # construct the formatter formatter = HtmlFormatter(linenos=False, cssclass="source") # style and formatting css = HtmlFormatter().get_style_defs('.source') highlighted_code = highlight(code, lexer, formatter) page = """ $ python pygments_demo.py > text.html <html> <head><style>{css}</style></head> <body>{highlighted_code}</body> </html> """.format(css=css, highlighted_code=highlighted_code) print(page)
  • 49. Output of the program from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import HtmlFormatter text.html if __name__ == '__main__': # get this file code = open("pygments_demo.py", "rw").read() # figure out the lexer lexer = get_lexer_by_name("python", stripall=True) # construct the formatter formatter = HtmlFormatter(linenos=False, cssclass="source") # style and formatting css = HtmlFormatter().get_style_defs('.source') highlighted_code = highlight(code, lexer, formatter) page = """ <html> <head><style>{css}</style></head> <body>{highlighted_code}</body> </html> """.format(css=css, highlighted_code=highlighted_code) print(page)
  • 50. #17 Work with Relational Databases (my_env)$ pip install django from datetime import datetime Internationalization! from django.contrib.auth.models import User from django.db import models from django.utils.translation import ugettext_lazy as _ class Post(models.Model): author = models.ForeignKey(User) title = models.CharField(_('Title'), max_length=100) content = models.TextField(_("Content")) pub_date = models.DateTimeField(_("Publication date")) class Comment(models.Model): post = models.ForeignKey(Post) name = models.CharField(_('Title'), max_length=100) content = models.TextField(_("Content"))
  • 51. #18 Work with NoSQL (my_env)$ pip install pymongo >>> import pymongo >>> connection = pymongo.Connection("localhost", 27017) >>> db = connection.test >>> db.name u'test' >>> db.my_collection Collection(Database(Connection('localhost', 27017), u'test'), u'my_collection') >>> db.my_collection.save({"x": 10}) ObjectId('4aba15ebe23f6b53b0000000') >>> db.my_collection.save({"x": 8}) ObjectId('4aba160ee23f6b543e000000') >>> db.my_collection.save({"x": 11}) ObjectId('4aba160ee23f6b543e000002') >>> db.my_collection.find_one() {u'x': 10, u'_id': ObjectId('4aba15ebe23f6b53b0000000')} >>> db.my_collection.create_index("x") u'x_1' >>> [item["x"] for item in db.my_collection.find().limit(2).skip(1)] [8, 11]
  • 52. #19 Message Queues (my_env)$ pip install celery==2.4.6 (my_env)$ pip install requests==0.9.2 import logging products/tasks.py import requests from celery import task from products.models import Product Decorators wrap a logger = logging.getLogger('products.tasks') function or method @task def check_all_images(): with a function. for product in Product.objects.all(): response = request.get(product.medium_image.url) if response.status_code != 200: msg = "Product {0} missing image".format(product.id) logging.warning(msg) >>> from products.tasks import confirm_all_images >>> result = confirm_all_images.delay() >>> result.ready() False >>> result.ready() True
  • 53. #20 Work with JSON >>> import json >>> data = { 'name':'Daniel Greenfeld', 'nickname':'pydanny', 'states_lived':['CA','KS','MD','NJ','VA','AD'], 'fiancee':'Audrey Roy' } >>> type(data) <type 'dict'> >>> payload = json.dumps(data) >>> payload '{"fiancee": "Audrey Roy", "nickname": "pydanny", "name": "Daniel Greenfeld", "states_lived": ["CA", "KS", "MD", "NJ", "VA", "AD"]}' >>> type(payload) <type 'str'> >>> restored = json.loads(payload) >>> type(restored) <type 'dict'> >>> restored {u'fiancee': u'Audrey Roy', u'nickname': u'pydanny', u'name': u'Daniel Greenfeld', u'states_lived': [u'CA', u'KS', u'MD', u'NJ', u'VA', u'AD' ]}
  • 54. #21 Serve the Web $ pip install ļ¬‚ask==0.8 # webapp.py from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run() ļ¬‚ask.pocoo.org
  • 55. #21 Serve the Web Lots more frameworks!
  • 56. #21 Serve the Web http://science.nasa.gov/
  • 57. #21 Serve the Web http://djangopackages.com http://opencomparison.org
  • 58. #21 Serve the Web http://consumernotebook.com
  • 59. #21 Serve the Web http://grove.io Hosted IRC
  • 60. Finis ā€¢ Learn more at the following booths: ā€¢ Python ā€¢ Django ā€¢ Pyladies