SlideShare a Scribd company logo
Intro to Python



Peter Krenesky
Lead Software Engineer


                     Slides: http://bit.ly/nXwnzQ
Why Python?

●   Easy to learn.
●   Easy to read.
●   Large selection of stable libraries.


    Much easier to build and maintain complex
    system infrastructure than bash scripts.


                          Slides: http://bit.ly/nXwnzQ
The Basics
●   Python is a dynamic language

●   primitives: int, str, float
●   but even literals are objects

    >>> x = 1
    >>> print type(x)
    <type 'int'>
Nulls in Python

●   All variables must have a value
●   None is python's equivalent of a Null


    >>> x = None
    >>> print x is None
    True
Strings

x = “a string”
z = str(1)

# string concatenation
“, ”.join([x, y])

# string prefixes (types)
u”A Unicode String”
r”A raw string, ignores / escapes!”
Strings: Formatting

# Single variable
“formated: %s” % x
# tuple of multiple variables
“%s formated %s” % (x, y)
# dictionary of variables
“%(foo)s formated %(foo)s” % {'foo':1}
#format string
format = ”format: %s”
format % x
Basic Data Structures

●   tuple: (1, 2, 3)

●   list:   [1, 2, 3]

●   dict:   {“a”:1, “b”:2, “c”:3}
Data Structures: dict

# create
d = {'a':1, 'b':2}
d = dict(a=1, b=2)

# add / update
d['a'] = 2
d['c'] = 3

# remove items
del d['a']

# iterators of keys, values, or both
d.keys()
d.values()
d.items()
Data Structures: tuple

#   create a tuple (immutable list)
t   = ()
t   = (1, 2, 3)
t   = tuple(iterable)
# indexable
x = t[1]
# implicit tuple creation
t = 1, 2, 3
# unpacking
a, b, c = t
Data Structures: list

# create
x = [1, 2, 3]
x = list(iterable)
# add items
x.append(item)
x.insert(position, item)
# remove items
x.remove(item)
x.pop()
Data Structures: slices

>>> x = [0, 1, 2, 3, 4]
>>> print x[1:3]
[1, 2]

>>> print x[1:]
[1, 2, 3, 4]

>>> print x[:2]
[0, 1]

>>> print x[0:5:2]
[0, 2, 4]

>>> print x[-1]
4
Data Structures: etc.

●   Queue – for making queues
●   Deque – double ended queues
●   OrderedDict – dictionary that maintains order
●   Named Tuples – tuples with named fields

●   DefaultDict – tools for building dictionaries
●   Itertools – tools for quickly iterating lists
Classes

class Vehicle(object):
    “”” something that can move “””

   x = 0
   y = 0
   z = 0
Classes: methods

class Vehicle(object):
    “”” something that can move “””

   x = 0
   y = 0
   z = 0

   def move(self, x, y, z):
       “”” makes the vehicle move “””
       self.x = x
       self.y = y
       self.z = z

       return x, y, z
Classes: Inheritance


class Car(Vehicle):

   def move(self, x, y):
       super(Car, self).move(x, y, self.z)
Classes: initializers

class Car(Vehicle):

   def __init__(self, x, y):
       “”” init a car “””
       super(Car, self).__init__(x, y, 0)
Classes: “magic” methods


__getitem__ makes a class indexable
__setitem__

__iter__ makes a class iterable

__call__ makes a class callable

__add__ math functions
__sub__
Doc Strings

class Vehicle(object):
    “”” something that can move “””

   X = 0
   Y = 0

   def move(self, x, y):
       “”” makes the vehicle move “””
       self.x = x
       self.y = y
Doc Strings: help()

>>> help(Vehicle)
Help on class Vehicle in module __main__:
class Vehicle(__builtin__.object)
 | something that can move
 |
 | Data descriptors defined here:
 |
 | __dict__
 |       dictionary for instance variables (if
defined)
 |
 | __weakref__
 |       list of weak references to the object (if
defined)
Methods: default args

def move(self, x, y, z=0, rate=1):
    self.x = x
    self.y = y
    self.z = z


>>> # move just x and y
>>> move(1, 1)

>>> # move z too
>>> move(1, 1, 1)

>>> # custom rate, but no z movement
>>> move(1, 1, rate=42)
Methods: args & kwargs

def foo(*args, **kwargs):
   print args
   print kwargs


>>> foo(1, 2, 3, a=4, b=5)
(1, 2, 3)
{'a':4, 'b':5}
Methods: kwargs common use
        unknown set of arguments




>>> print dict(a=1, b=2, c=3)
{“a”:1, “b”:2, “c”=3}
Methods: arg & kwarg unpacking

def foo(a, b, c, d, e):
   print a, b, c, d, e



>>> t = (1,2,3)
>>> d = {'d':4, 'e':5}
>>> foo(*t, **d)

(1, 2, 3, 4, 5)
Methods: kwargs common use
                Method overloading

class Vehicle():
  def __init__(self, x, y, z=0):
        self.x, self.y, self.z = x, y, z


class TimeMachine(Vehicle):
    def __init__(self, ts, *args, **kw):
        super(Car, self).__init__(*args, **kw)
        self.ts = ts


 >>> from datetime import datetime
 >>> ts = datetime.now()
 >>> delorean = TimeMachine(ts, 1, 2, 3)
 >>> print delorean.x, delorean.y, delorean.z
 1, 2, 3
If statements

if 5 in list:
   print '5 was found'

elif 10 in list:
   print '10 was found'

else:
    print 'no 5 or 10'


# ternary (in-line)
five = True if 5 in list else False
Identity vs. Value

>>> foo = None
>>> print foo is None
True


>>> car1 = Car(id=123)
>>> car2 = Car(id=123)
>>> print car1 == car2
True

>>> print car1 is car2
False
Sequences as booleans

>>> empty = []
>>> full = [1, 2, 3]
>>> print bool(empty)
False

>>> print bool(full)
True


>>> print bool(“”) or {}
False
__contains__

>>> foo = [1, 2, 3]
>>> print 2 in foo
True


>>> bar = dict(a=1, b=2, c=3)
>>> print “d” in bar
False
Iteration

for i in iterable:
    print i



for i in range(10):
    if i == 10:
        break
    elif i == 5:
        continue
    print i
Iteration: dicts

# iterating a dict lists its keys
for key in dict:
    print key


# items returns a tuple
# which can be unpacked during iteration
for key, value in dict.items():
  print key, value
Exceptions

try:
       raise Exception('intentional!')

except Exception, e:
    print 'handle exception'

else:
    print 'no exception occurred'

finally:
    print 'this always runs'
List Comprehensions

>>> [i**2 for i in range(3)]
[0, 1, 4]



>>> [i**2 for i in range(3) if i > 0]
[1, 4]


>>> (i for i in range(3))
<generator object <genexpr> at 0xf717d13>
Generators

def foo():
    for i in range(2):
         yield i


>>> gen = foo()
>>> gen.next()
0

>>> gen.next()
1

>>> gen.next()
StopIteration
Generators: more useful example


              /



      var    etc    bin
Generators: more useful example

def dfs(tree):
    “”” depth first traversal “””
    yield tree

   if tree.children:
       for child in tree.children:
           for node in dfs(child):
               yield node

def search(tree, value):
    for node in dfs(tree)
        if value == node.value:
            return True

   return False
Scopes
GLOBAL_VARS = [1, 2]
print GLOBAL_VARS


class Foo():
    class_scope = [3, 4]

   def bar(self, class_scope_too=[5, 6]):
       local_scope = [7, 8]

       class_scope_too += local_scope
       print class_scope_too
Scopes: imports are global scope


from foo import GLOBAL_ARGS
Questions?

Slides:
http://bit.ly/nXwnzQ


Peter Krenesky
Email:     peter@osuosl.org
twitter: @kreneskyp

More Related Content

What's hot

Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
niklal
 
Python for text processing
Python for text processingPython for text processing
Python for text processing
Xiang Li
 

What's hot (20)

Python in 90 minutes
Python in 90 minutesPython in 90 minutes
Python in 90 minutes
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basics
 
AmI 2016 - Python basics
AmI 2016 - Python basicsAmI 2016 - Python basics
AmI 2016 - Python basics
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In Python
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlow
 
Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutes
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heaven
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
 
Python
PythonPython
Python
 
Python 101 1
Python 101   1Python 101   1
Python 101 1
 
Python in 30 minutes!
Python in 30 minutes!Python in 30 minutes!
Python in 30 minutes!
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
 
Python for text processing
Python for text processingPython for text processing
Python for text processing
 
Python Part 2
Python Part 2Python Part 2
Python Part 2
 
python.ppt
python.pptpython.ppt
python.ppt
 
Python introduction
Python introductionPython introduction
Python introduction
 

Viewers also liked

Hosting Open Source Projects at the OSUOSL
Hosting Open Source Projects at the OSUOSLHosting Open Source Projects at the OSUOSL
Hosting Open Source Projects at the OSUOSL
OSU Open Source Lab
 
java programming basics - part ii
 java programming basics - part ii java programming basics - part ii
java programming basics - part ii
jyoti_lakhani
 

Viewers also liked (20)

Fundamentals of Open Source Development
Fundamentals of Open Source DevelopmentFundamentals of Open Source Development
Fundamentals of Open Source Development
 
Embedded Systems
Embedded SystemsEmbedded Systems
Embedded Systems
 
Linux basics (part 2)
Linux basics (part 2)Linux basics (part 2)
Linux basics (part 2)
 
Hosting Open Source Projects at the OSUOSL
Hosting Open Source Projects at the OSUOSLHosting Open Source Projects at the OSUOSL
Hosting Open Source Projects at the OSUOSL
 
Linux basics (part 1)
Linux basics (part 1)Linux basics (part 1)
Linux basics (part 1)
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
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)
 
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
 
java programming basics - part ii
 java programming basics - part ii java programming basics - part ii
java programming basics - part ii
 
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
 
Python Is Rad
Python Is RadPython Is Rad
Python Is Rad
 
Python
Python Python
Python
 
Teaching Kids Programming using Agile Practices
Teaching Kids Programming using Agile PracticesTeaching Kids Programming using Agile Practices
Teaching Kids Programming using Agile Practices
 
Kids liketocode
Kids liketocodeKids liketocode
Kids liketocode
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
 
CON 3431 - Introducing Java Programming to Kids
CON 3431 - Introducing Java Programming to KidsCON 3431 - Introducing Java Programming to Kids
CON 3431 - Introducing Java Programming to Kids
 
Teach your kids how to program with Python and the Raspberry Pi
Teach your kids how to program with Python and the Raspberry PiTeach your kids how to program with Python and the Raspberry Pi
Teach your kids how to program with Python and the Raspberry Pi
 
Kids computer-programming
Kids computer-programmingKids computer-programming
Kids computer-programming
 

Similar to Intro to Python

Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)
gekiaruj
 

Similar to Intro to Python (20)

Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)
 
Chapter 02 functions -class xii
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
Introduction to python programming 1
Introduction to python programming   1Introduction to python programming   1
Introduction to python programming 1
 
Python classes in mumbai
Python classes in mumbaiPython classes in mumbai
Python classes in mumbai
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
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
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slide
 
Python basic
Python basicPython basic
Python basic
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheet
 
sonam Kumari python.ppt
sonam Kumari python.pptsonam Kumari python.ppt
sonam Kumari python.ppt
 
Becoming a Pythonist
Becoming a PythonistBecoming a Pythonist
Becoming a Pythonist
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05c
 

Recently uploaded

Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Accounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfAccounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdf
YibeltalNibretu
 
Industrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training ReportIndustrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training Report
Avinash Rai
 

Recently uploaded (20)

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
NLC-2024-Orientation-for-RO-SDO (1).pptx
NLC-2024-Orientation-for-RO-SDO (1).pptxNLC-2024-Orientation-for-RO-SDO (1).pptx
NLC-2024-Orientation-for-RO-SDO (1).pptx
 
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdfDanh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
 
Forest and Wildlife Resources Class 10 Free Study Material PDF
Forest and Wildlife Resources Class 10 Free Study Material PDFForest and Wildlife Resources Class 10 Free Study Material PDF
Forest and Wildlife Resources Class 10 Free Study Material PDF
 
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 
Salient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxSalient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptx
 
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptxSolid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Accounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfAccounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Industrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training ReportIndustrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training Report
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
 
Advances in production technology of Grapes.pdf
Advances in production technology of Grapes.pdfAdvances in production technology of Grapes.pdf
Advances in production technology of Grapes.pdf
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
 
2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx
 
[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation
 

Intro to Python

  • 1. Intro to Python Peter Krenesky Lead Software Engineer Slides: http://bit.ly/nXwnzQ
  • 2. Why Python? ● Easy to learn. ● Easy to read. ● Large selection of stable libraries. Much easier to build and maintain complex system infrastructure than bash scripts. Slides: http://bit.ly/nXwnzQ
  • 3. The Basics ● Python is a dynamic language ● primitives: int, str, float ● but even literals are objects >>> x = 1 >>> print type(x) <type 'int'>
  • 4. Nulls in Python ● All variables must have a value ● None is python's equivalent of a Null >>> x = None >>> print x is None True
  • 5. Strings x = “a string” z = str(1) # string concatenation “, ”.join([x, y]) # string prefixes (types) u”A Unicode String” r”A raw string, ignores / escapes!”
  • 6. Strings: Formatting # Single variable “formated: %s” % x # tuple of multiple variables “%s formated %s” % (x, y) # dictionary of variables “%(foo)s formated %(foo)s” % {'foo':1} #format string format = ”format: %s” format % x
  • 7. Basic Data Structures ● tuple: (1, 2, 3) ● list: [1, 2, 3] ● dict: {“a”:1, “b”:2, “c”:3}
  • 8. Data Structures: dict # create d = {'a':1, 'b':2} d = dict(a=1, b=2) # add / update d['a'] = 2 d['c'] = 3 # remove items del d['a'] # iterators of keys, values, or both d.keys() d.values() d.items()
  • 9. Data Structures: tuple # create a tuple (immutable list) t = () t = (1, 2, 3) t = tuple(iterable) # indexable x = t[1] # implicit tuple creation t = 1, 2, 3 # unpacking a, b, c = t
  • 10. Data Structures: list # create x = [1, 2, 3] x = list(iterable) # add items x.append(item) x.insert(position, item) # remove items x.remove(item) x.pop()
  • 11. Data Structures: slices >>> x = [0, 1, 2, 3, 4] >>> print x[1:3] [1, 2] >>> print x[1:] [1, 2, 3, 4] >>> print x[:2] [0, 1] >>> print x[0:5:2] [0, 2, 4] >>> print x[-1] 4
  • 12. Data Structures: etc. ● Queue – for making queues ● Deque – double ended queues ● OrderedDict – dictionary that maintains order ● Named Tuples – tuples with named fields ● DefaultDict – tools for building dictionaries ● Itertools – tools for quickly iterating lists
  • 13. Classes class Vehicle(object): “”” something that can move “”” x = 0 y = 0 z = 0
  • 14. Classes: methods class Vehicle(object): “”” something that can move “”” x = 0 y = 0 z = 0 def move(self, x, y, z): “”” makes the vehicle move “”” self.x = x self.y = y self.z = z return x, y, z
  • 15. Classes: Inheritance class Car(Vehicle): def move(self, x, y): super(Car, self).move(x, y, self.z)
  • 16. Classes: initializers class Car(Vehicle): def __init__(self, x, y): “”” init a car “”” super(Car, self).__init__(x, y, 0)
  • 17. Classes: “magic” methods __getitem__ makes a class indexable __setitem__ __iter__ makes a class iterable __call__ makes a class callable __add__ math functions __sub__
  • 18. Doc Strings class Vehicle(object): “”” something that can move “”” X = 0 Y = 0 def move(self, x, y): “”” makes the vehicle move “”” self.x = x self.y = y
  • 19. Doc Strings: help() >>> help(Vehicle) Help on class Vehicle in module __main__: class Vehicle(__builtin__.object) | something that can move | | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined)
  • 20. Methods: default args def move(self, x, y, z=0, rate=1): self.x = x self.y = y self.z = z >>> # move just x and y >>> move(1, 1) >>> # move z too >>> move(1, 1, 1) >>> # custom rate, but no z movement >>> move(1, 1, rate=42)
  • 21. Methods: args & kwargs def foo(*args, **kwargs): print args print kwargs >>> foo(1, 2, 3, a=4, b=5) (1, 2, 3) {'a':4, 'b':5}
  • 22. Methods: kwargs common use unknown set of arguments >>> print dict(a=1, b=2, c=3) {“a”:1, “b”:2, “c”=3}
  • 23. Methods: arg & kwarg unpacking def foo(a, b, c, d, e): print a, b, c, d, e >>> t = (1,2,3) >>> d = {'d':4, 'e':5} >>> foo(*t, **d) (1, 2, 3, 4, 5)
  • 24. Methods: kwargs common use Method overloading class Vehicle(): def __init__(self, x, y, z=0): self.x, self.y, self.z = x, y, z class TimeMachine(Vehicle): def __init__(self, ts, *args, **kw): super(Car, self).__init__(*args, **kw) self.ts = ts >>> from datetime import datetime >>> ts = datetime.now() >>> delorean = TimeMachine(ts, 1, 2, 3) >>> print delorean.x, delorean.y, delorean.z 1, 2, 3
  • 25. If statements if 5 in list: print '5 was found' elif 10 in list: print '10 was found' else: print 'no 5 or 10' # ternary (in-line) five = True if 5 in list else False
  • 26. Identity vs. Value >>> foo = None >>> print foo is None True >>> car1 = Car(id=123) >>> car2 = Car(id=123) >>> print car1 == car2 True >>> print car1 is car2 False
  • 27. Sequences as booleans >>> empty = [] >>> full = [1, 2, 3] >>> print bool(empty) False >>> print bool(full) True >>> print bool(“”) or {} False
  • 28. __contains__ >>> foo = [1, 2, 3] >>> print 2 in foo True >>> bar = dict(a=1, b=2, c=3) >>> print “d” in bar False
  • 29. Iteration for i in iterable: print i for i in range(10): if i == 10: break elif i == 5: continue print i
  • 30. Iteration: dicts # iterating a dict lists its keys for key in dict: print key # items returns a tuple # which can be unpacked during iteration for key, value in dict.items(): print key, value
  • 31. Exceptions try: raise Exception('intentional!') except Exception, e: print 'handle exception' else: print 'no exception occurred' finally: print 'this always runs'
  • 32. List Comprehensions >>> [i**2 for i in range(3)] [0, 1, 4] >>> [i**2 for i in range(3) if i > 0] [1, 4] >>> (i for i in range(3)) <generator object <genexpr> at 0xf717d13>
  • 33. Generators def foo(): for i in range(2): yield i >>> gen = foo() >>> gen.next() 0 >>> gen.next() 1 >>> gen.next() StopIteration
  • 34. Generators: more useful example / var etc bin
  • 35. Generators: more useful example def dfs(tree): “”” depth first traversal “”” yield tree if tree.children: for child in tree.children: for node in dfs(child): yield node def search(tree, value): for node in dfs(tree) if value == node.value: return True return False
  • 36. Scopes GLOBAL_VARS = [1, 2] print GLOBAL_VARS class Foo(): class_scope = [3, 4] def bar(self, class_scope_too=[5, 6]): local_scope = [7, 8] class_scope_too += local_scope print class_scope_too
  • 37. Scopes: imports are global scope from foo import GLOBAL_ARGS