SlideShare a Scribd company logo
90% of Python in 90 Minutes
@__mharrison__
Copyright 2013
About Me
●

●

●

12+ years Python
Worked in Data Analysis, HA, Search,
Open Source, BI, and Storage
Author of multiple Python Books
Goal
●

Read Python

●

Write Python
Book
Book
Treading on Python Volume 1 covers this
talk in much more detail.
Begin
Disclaimer
●

Assume some programming experience

●

Not covering all api's, just syntax
Warning
●

Starting from ground zero

●

Hands-on at end
Three Python'isms to Remember
●

dir

●

help

●

colon/indent shuffle
Why Python?
Python is a powerful, multi-paradigm,
interpreted language popular with
start-ups and large Co’s
Python 2 or 3?
For beginners there is no real difference
between Python 2 & 3. The basics are the
same (except for print)
Hello World
hello world
print "hello world"
from interpreter
$ python
>>> print "hello world"
hello world
REPL
Read, Eval, Print, Loop
REPL
$ python
>>> 2 + 2
4
>>>

#
#
#

read, eval
print
repeat (loop)
REPL (2)
Many developers keep a REPL handy
during programming
From script
Make file hello.py with
print "hello world"
Run with:
python hello.py
(unix) script
Make file hello with
#!/usr/bin/env python
print "hello world"
Run with:
chmod +x hello
./hello
Python 3 hello world
print is no longer a statement, but a
function
print("hello world")
Objects
Objects
Everything in Python is an object that has:
●

an identity (id)

●

a value (mutable or immutable)
id
>>> a = 4
>>> id(a)
6406896
Value
●

●

Mutable:When you alter the item, the
id is still the same. Dictionary, List
Immutable:String, Integer, Tuple
Mutable
>>> b = []
>>> id(b)
140675605442000
>>> b.append(3)
>>> b
[3]
>>> id(b)
140675605442000

# SAME!
Immutable
>>> a = 4
>>> id(a)
6406896
>>> a = a + 1
>>> id(a)
6406872
# DIFFERENT!
Variables
a
b
c
a

=
=
=
=

4
# Integer
5.6
# Float
"hello" # String
"4"
# rebound to String
Naming
●

lowercase

●

underscore_between_words

●

don't start with numbers

See PEP 8
PEP
Python Enhancement Proposal (similar to
JSR in Java)
Math
Math
+, -, *, /, ** (power), % (modulo)
Careful with integer division
>>> 3/4
0
>>> 3/4.
0.75
(In Python 3 // is integer division
operator)
What happens when you
raise 10 to the 100th?
Long
>>> 10**100
10000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000L
Long (2)
>>> import sys
>>> sys.maxint
9223372036854775807
>>> sys.maxint + 1
9223372036854775808L
Strings
Strings
name = 'matt'
with_quote = "I ain't gonna"
longer = """This string has
multiple lines
in it"""
How do I print?
He said, “I’m sorry”
String escaping
Escape with 
>>> print 'He said, "I'm sorry"'
He said, "I'm sorry"
>>> print '''He said, "I'm sorry"'''
He said, "I'm sorry"
>>> print """He said, "I'm sorry""""
He said, "I'm sorry"
String escaping (2)
Escape Sequence

Output



Backslash

'

Single quote

"

Double quote

b

ASCII Backspace

n

Newline

t

Tab

u12af

Unicode 16 bit

U12af89bc

Unicode 32 bit

o84

Octal character

xFF

Hex character
String formatting
c-like
>>> "%s %s" %('hello', 'world')
'hello world'

PEP 3101 style
>>> "{0} {1}".format('hello', 'world')
'hello world'
Methods & dir
dir
Lists attributes and methods:
>>> dir("a string")
['__add__', '__class__', ... 'startswith',
'swapcase', 'title', 'translate', 'upper',

'strip',
'zfill']
Whats with all the
'__blah__'?
dunder methods
dunder (double under) or "special/magic"
methods determine what will happen
when + (__add__) or / (__div__) is
called.
help
>>> help("a string".startswith)
Help on built-in function startswith:
startswith(...)
S.startswith(prefix[, start[, end]]) -> bool
Return True if S starts with the specified prefix, False
otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.
String methods
●

s.endswith(sub)
Returns True if endswith sub

●

s.find(sub)
Returns index of sub or -1

●

s.format(*args)
Places args in string
String methods (2)
●

s.index(sub)
Returns index of sub or exception

●

s.join(list)
Returns list items separated by string

●

s.strip()
Removes whitespace from start/end
Comments
comments
Comments follow a #
comments
No multi-line comments
More Types
None
Pythonic way of saying NULL. Evaluates
to False.
c = None
booleans
a = True
b = False
sequences
●

lists

●

tuples

●

sets
lists
Hold sequences.
How would we find out the attributes &
methods of a list?
lists
>>> dir([])
['__add__', '__class__', '__contains__',...
'__iter__',... '__len__',... , 'append', 'count',
'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']
lists
>>>
>>>
>>>
>>>
>>>
>>>
[1,

a = []
a.append(4)
a.append('hello')
a.append(1)
a.sort() # in place
print a
4, 'hello']
lists
How would we find out documentation
for a method?
lists
help function:
>>> help([].append)
Help on built-in function append:
append(...)
L.append(object) -- append object to end
List methods
●

l.append(x)
Insert x at end of list

●

l.extend(l2)
Add l2 items to list

●

l.sort()
In place sort
List methods (2)
●

l.reverse()
Reverse list in place

●

l.remove(item)
Remove first item found

●

l.pop()
Remove/return item at end of list
Dictionaries
dictionaries
Also called hashmap or associative array
elsewhere
>>>
>>>
>>>
>>>
>>>
10

age = {}
age['george'] = 10
age['fred'] = 12
age['henry'] = 10
print age['george']
dictionaries (2)
Find out if 'matt' in age
>>> 'matt' in age
False
in statement
Uses __contains__ dunder method to
determine membership. (Or __iter__ as
fallback)
.get
>>> print age['charles']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'charles'
>>> print age.get('charles', 'Not found')
Not found
deleting keys
Removing 'charles' from age
>>> del age['charles']
deleting keys
del not in dir. .pop is an alternative
Functions
functions
def add_2(num):
""" return 2
more than num
"""
return num + 2
five = add_2(3)
functions (2)
●

def

●

function name

●

(parameters)

●

: + indent

●

optional documentation

●

body

●

return
whitespace
Instead of { use a : and indent
consistently (4 spaces)
whitespace (2)
invoke python -tt to error out during
inconsistent tab/space usage in a file
default (named) parameters
def add_n(num, n=3):
"""default to
adding 3"""
return num + n
five = add_n(2)
ten = add_n(15, -5)
__doc__
Functions have docstrings. Accessible
via .__doc__ or help
__doc__
>>> def echo(txt):
...
"echo back txt"
...
return txt
>>> help(echo)
Help on function echo in module __main__:
<BLANKLINE>
echo(txt)
echo back txt
<BLANKLINE>
naming
●

lowercase

●

underscore_between_words

●

don't start with numbers

●

verb

See PEP 8
Conditionals
conditionals
if grade > 90:
print "A"
elif grade > 80:
print "B"
elif grade > 70:
print "C"
else:
print "D"
Remember the
colon/whitespace!
Booleans
a = True
b = False
Comparison Operators
Supports (>, >=, <, <=, ==, !=)
>>> 5 > 9
False
>>> 'matt' != 'fred'
True
>>> isinstance('matt',
basestring)
True
Boolean Operators
and, or, not (for logical), &, |, and ^ (for
bitwise)
>>> x = 5
>>> x < -4 or x > 4
True
Boolean note
Parens are only required for precedence
if (x > 10):
print "Big"
same as
if x > 10:
print "Big"
Chained comparisons
if 3 < x < 5:
print "Four!"
Same as
if x > 3 and x < 5:
print "Four!"
Iteration
iteration
for number in [1,2,3,4,5,6]:
print number
for number in range(1, 7):
print number
range note
Python tends to follow half-open interval
([start,end)) with range and slices.
●

end - start = length

●

easy to concat ranges w/o overlap
iteration (2)
Java/C-esque style of object in array
access (BAD):
animals = ["cat", "dog", "bird"]
for index in range(len(animals)):
print index, animals[index]
iteration (3)
If you need indices, use enumerate
animals = ["cat", "dog", "bird"]
for index, value in enumerate(animals):
print index, value
iteration (4)
Can break out of nearest loop
for item in sequence:
# process until first negative
if item < 0:
break
# process item
iteration (5)
Can continue to skip over items
for item in sequence:
if item < 0:
continue
# process all positive items
iteration (6)
Can loop over lists, strings, iterators,
dictionaries... sequence like things:
my_dict = { "name": "matt", "cash": 5.45}
for key in my_dict.keys():
# process key
for value in my_dict.values():
# process value
for key, value in my_dict.items():
# process items
pass
pass is a null operation
for i in
# do
pass

range(10):
nothing 10 times
Hint
Don't modify list or dictionary contents
while looping over them
Slicing
Slicing
Sequences (lists, tuples, strings, etc) can
be sliced to pull out a single item
my_pets = ["dog", "cat", "bird"]
favorite = my_pets[0]
bird = my_pets[-1]
Negative Indexing
Proper way to think of [negative
indexing] is to reinterpret a[-X] as
a[len(a)-X]
@gvanrossum
Slicing (2)
Slices can take an end index, to pull out a
list of items
my_pets = ["dog", "cat", "bird"]
# a list
cat_and_dog = my_pets[0:2]
cat_and_dog2 = my_pets[:2]
cat_and_bird = my_pets[1:3]
cat_and_bird2 = my_pets[1:]
Slicing (3)
Slices can take a stride
my_pets = ["dog", "cat", "bird"]
# a list
dog_and_bird = [0:3:2]
zero_three_etc = range(0,10)
[::3]
Slicing (4)
Just to beat it in
veg = "tomatoe"
correct = veg[:-1]
tmte = veg[::2]
eotamot = veg[::-1]
File IO
File Input
Open a file to read from it (old style):
fin = open("foo.txt")
for line in fin:
# manipulate line
fin.close()
File Output
Open a file using 'w' to write to a file:
fout = open("bar.txt", "w")
fout.write("hello world")
fout.close()
Always remember to
close your files!
closing with with
implicit close (new 2.5+ style)
with open('bar.txt') as fin:
for line in fin:
# process line
Classes
Classes
class Animal(object):
def __init__(self, name):
self.name = name
def talk(self):
print "Generic Animal Sound"
animal = Animal("thing")
animal.talk()
Classes (2)
notes:
●

object (base class) (fixed in 3.X)

●

dunder init (constructor)

●

all methods take self as first parameter
Classes(2)
Subclassing
class Cat(Animal):
def talk(self):
print '%s says, "Meow!"' % (self.name)
cat = Cat("Groucho")
cat.talk() # invoke method
Classes(3)
class Cheetah(Cat):
"""classes can have
docstrings"""
def talk(self):
print "Growl"
naming
●

CamelCase

●

don't start with numbers

●

Nouns
Debugging
Poor mans
print works a lot of the time
Remember
Clean up print statements. If you really
need them, use logging or write to
sys.stdout
pdb
import pdb; pdb.set_trace()
pdb commands
●

h - help

●

s - step into

●

n - next

●

c - continue

●

w - where am I (in stack)?

●

l - list code around me
That's all
Questions? Tweet me
For more details see
Treading on Python Volume 1
@__mharrison__
http://hairysun.com

More Related Content

PPTX
Intro to Python Programming Language
PDF
Python File Handling | File Operations in Python | Learn python programming |...
PPTX
PDF
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
PPT
Introduction to python
PPT
Introduction to Python
PDF
Python Workshop
PPTX
Python Tutorial Part 1
Intro to Python Programming Language
Python File Handling | File Operations in Python | Learn python programming |...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Introduction to python
Introduction to Python
Python Workshop
Python Tutorial Part 1

What's hot (20)

PDF
Python Basics
PPTX
Python Scipy Numpy
PPT
Introduction to Python
PPT
Python ppt
PDF
Python programming : Classes objects
PDF
Python list
PPTX
Python
PDF
Introduction to python programming
PPTX
Functions in Python
PDF
Python basic
PDF
Basic Concepts in Python
PPTX
Introduction to-python
PPTX
Python
PDF
Introduction to IPython & Jupyter Notebooks
PDF
Datatypes in python
PDF
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
PPT
Python Programming ppt
PPTX
Python: Modules and Packages
PDF
Python programming : Strings
PDF
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Basics
Python Scipy Numpy
Introduction to Python
Python ppt
Python programming : Classes objects
Python list
Python
Introduction to python programming
Functions in Python
Python basic
Basic Concepts in Python
Introduction to-python
Python
Introduction to IPython & Jupyter Notebooks
Datatypes in python
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Programming ppt
Python: Modules and Packages
Python programming : Strings
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Ad

Viewers also liked (20)

PPTX
Python 101: Python for Absolute Beginners (PyTexas 2014)
ODP
Python Presentation
DOCX
Build Your Own SaaS using Docker
PDF
Embedded C programming based on 8051 microcontroller
PDF
Fast ALS-Based Matrix Factorization for Recommender Systems
PPTX
Introduction to python for Beginners
PPTX
Python PPT
PPTX
Understanding AntiEntropy in Cassandra
PDF
Cassandra London March 2016 - Lightening talk - introduction to incremental ...
PDF
Real World Tales of Repair (Alexander Dejanovski, The Last Pickle) | Cassandr...
PDF
Spotify: Automating Cassandra repairs
PDF
Linux Performance Analysis and Tools
PPTX
Advance OOP concepts in Python
PDF
Python 2 vs. Python 3
PDF
Python Tricks That You Can't Live Without
PPTX
Basics of Object Oriented Programming in Python
PDF
LISA17 Container Performance Analysis
PDF
Python的50道陰影
PPTX
連淡水阿嬤都聽得懂的 機器學習入門 scikit-learn
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python Presentation
Build Your Own SaaS using Docker
Embedded C programming based on 8051 microcontroller
Fast ALS-Based Matrix Factorization for Recommender Systems
Introduction to python for Beginners
Python PPT
Understanding AntiEntropy in Cassandra
Cassandra London March 2016 - Lightening talk - introduction to incremental ...
Real World Tales of Repair (Alexander Dejanovski, The Last Pickle) | Cassandr...
Spotify: Automating Cassandra repairs
Linux Performance Analysis and Tools
Advance OOP concepts in Python
Python 2 vs. Python 3
Python Tricks That You Can't Live Without
Basics of Object Oriented Programming in Python
LISA17 Container Performance Analysis
Python的50道陰影
連淡水阿嬤都聽得懂的 機器學習入門 scikit-learn
Ad

Similar to Learn 90% of Python in 90 Minutes (20)

PDF
Python in 90 Minutes
PDF
Python Quick Start
PPTX
Python chapter 2
PPTX
python chapter 1
PPT
Python programming tutorial for beginners
PPTX
Learn python in 20 minutes
PDF
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
PPT
ComandosDePython_ComponentesBasicosImpl.ppt
PPTX
Python Workshop
PPT
Python course in_mumbai
PPT
Python course in_mumbai
PPT
Python tutorial
PDF
Course notes on Astronomical data analysis by python pdf
PDF
Python 101 1
PDF
Presentation pythonpppppppppppppppppppppppppppppppppyyyyyyyyyyyyyyyyyyytttttt...
PPTX
2015 bioinformatics python_strings_wim_vancriekinge
PDF
Introduction to Python
PPTX
Introduction to python programming 1
PPTX
Python material
PPTX
Python Lecture 6
Python in 90 Minutes
Python Quick Start
Python chapter 2
python chapter 1
Python programming tutorial for beginners
Learn python in 20 minutes
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
ComandosDePython_ComponentesBasicosImpl.ppt
Python Workshop
Python course in_mumbai
Python course in_mumbai
Python tutorial
Course notes on Astronomical data analysis by python pdf
Python 101 1
Presentation pythonpppppppppppppppppppppppppppppppppyyyyyyyyyyyyyyyyyyytttttt...
2015 bioinformatics python_strings_wim_vancriekinge
Introduction to Python
Introduction to python programming 1
Python material
Python Lecture 6

Recently uploaded (20)

PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Modernizing your data center with Dell and AMD
PDF
Advanced Soft Computing BINUS July 2025.pdf
PPT
Teaching material agriculture food technology
PDF
Machine learning based COVID-19 study performance prediction
PDF
[발표본] 너의 과제는 클라우드에 있어_KTDS_김동현_20250524.pdf
PDF
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
KodekX | Application Modernization Development
PPTX
Big Data Technologies - Introduction.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Spectral efficient network and resource selection model in 5G networks
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
Chapter 3 Spatial Domain Image Processing.pdf
Modernizing your data center with Dell and AMD
Advanced Soft Computing BINUS July 2025.pdf
Teaching material agriculture food technology
Machine learning based COVID-19 study performance prediction
[발표본] 너의 과제는 클라우드에 있어_KTDS_김동현_20250524.pdf
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
KodekX | Application Modernization Development
Big Data Technologies - Introduction.pptx
Unlocking AI with Model Context Protocol (MCP)
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
NewMind AI Weekly Chronicles - August'25 Week I
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
20250228 LYD VKU AI Blended-Learning.pptx
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Spectral efficient network and resource selection model in 5G networks
“AI and Expert System Decision Support & Business Intelligence Systems”

Learn 90% of Python in 90 Minutes