Python Handbook
Python Handbook
Introduction
Preface
Introduction to Python
Installing Python
Running Python programs
Python 2 vs Python 3
The basics of working with Python
Data types
Operators
The Ternary Operator
Strings
Booleans
Numbers
Constants
Enums
User Input
Control statements
Lists
Tuples
Dictionaries
Sets
Functions
Objects
Loops
1
Classes
Modules
The Python Standard Library
The PEP8 Python style guide
Debugging
Variables scope
Accept arguments from the command line
Lambda functions
Recursion
Nested functions
Closures
Decorators
Docstrings
Introspection
Annotations
Exceptions
The with statement
Installing 3rd party packages using pip
List comprehensions
Polymorphism
Operator Overloading
Virtual Environments
Conclusion
2
Introduction
The Python Handbook follows the 80/20 rule: learn
80% of the topic in 20% of the time.
Enjoy!
3
Introduction to Python
Python is literally eating the programming world. It is
growing in popularity and usage in ways that are pretty
much unprecedented in the history of computers.
4
It is also appreciated by professionals across many
different fields.
5
Starting with Python is very easy. All you need is to
install the official package from python.org, for
Windows, macOS or Linux, and you're ready to go.
6
The language everyone interested in coding
should learn first.
7
Installing Python
Go to https://www.python.org, choose the Downloads
menu, choose your operating system and a panel with
a link to download the official package will appear:
8
Running Python
programs
There are a few different ways to run Python
programs.
Notice the >>> symbol, and the cursor after that. You
can type any Python code here, and press the enter
name = "Flavio"
9
print(name)
10
This might be more convenient for you because with
the mouse you can move around and copy/paste more
easily than with the terminal.
Install it with
Make sure the pip binaries are in your path, then run
ipython :
11
and then run it with python program.py
12
Then I can set execution permission on the file:
./program.py
13
After installing this extension you will have Python
code autocompletion and error checking, automatic
formatting and code linting with pylint , and some
special commands, including:
14
Python: Run Current File in Python Interactive
Window:
15
Another way to easily run Python code is to use repl.it,
a very nice website that provides a coding
environment you can create and run your apps on, in
any language, Python included:
16
and you will be immediately shown an editor with a
main.py file, ready to be filled with a lot of Python
code:
17
I think repl.it is handy because:
18
Python 2 vs Python 3
One key topic to talk about, right from the start, is the
Python 2 vs Python 3 discussion.
19
The basics of working
with Python
Variables
We can create a new Python variable by assigning a
value to a label, using the = assignment operator.
name = "Roger"
age = 8
name1
AGE
aGE
a11111
my_name
_name
20
123
test!
name%
Expressions and
statements
We can expression any sort of code that returns a
value. For example
1 + 1
"Roger"
name = "Roger"
print(name)
21
name = "Roger"; print(name)
Comments
In a Python program, everything after a hash mark is
ignored, and considered a comment:
Indentation
Indentation in Python is meaningful.
name = "Flavio"
print(name)
22
Data types
Python has several built-in types.
name = "Roger"
name = "Roger"
type(name) == str #True
Or using isinstance() :
name = "Roger"
isinstance(name, str) #True
We used the str class here, but the same works for
other data types.
23
age = 1
type(age) == int #True
fraction = 0.1
type(fraction) == float #True
name = "Flavio"
age = 20
name = str("Flavio")
anotherName = str(name)
age = int("20")
print(age) #20
fraction = 0.1
intFraction = int(fraction)
print(intFraction) #0
24
This is called casting. Of course this conversion might
not always work depending on the value passed. If
you write test instead of 20 in the above string,
you'll get a ValueError: invalid literal for int()
and more!
25
Operators
Python operators are symbols that we use to run
operations upon values and variables.
assignment operator
arithmetic operators
comparison operators
logical operators
bitwise operators
Assignment operator
The assignment operator is used to assign a value to
a variable:
age = 8
age = 8
anotherVariable = age
26
Arithmetic operators
Python has a number of arithmetic operators: + , - ,
1 + 1 #2
2 - 1 #1
2 * 2 #4
4 / 2 #2
4 % 3 #1
4 ** 2 #16
4 // 2 #2
print(-4) #-4
+=
-=
*=
/=
%=
..and so on
27
Example:
age = 8
age += 1
# age is now 9
Comparison operators
Python defines a few comparison operators:
==
!=
>
<
>=
<=
a = 1
b = 2
a == b #False
a != b #True
a > b #False
a <= b #True
Boolean operators
Python gives us the following boolean operators:
not
and
or
28
When working with True or False attributes, those
work like logical AND, OR and NOT, and are often
used in the if conditional expression evaluation:
condition1 = True
condition2 = False
print(0 or 1) ## 1
print(False or 'hey') ## 'hey'
print('hi' or 'hey') ## 'hi'
print([] or False) ## 'False'
print(False or []) ## '[]'
y, else x .
29
print(0 and 1) ## 0
print(1 and 0) ## 0
print(False and 'hey') ## False
print('hi' and 'hey') ## 'hey'
print([] and False ) ## []
print(False and [] ) ## False
x, else y .
Bitwise operators
Some operators are used to work on bits and binary
numbers:
30
The Ternary Operator
The ternary operator in Python allows you to quickly
define a conditional.
Instead of writing:
def is_adult(age):
if age > 18:
return True
else:
return False
def is_adult(age):
return True if age > 18 else False
31
Strings
A string in Python is a series of characters enclosed
into quotes or double quotes:
"Roger"
'Roger'
name = "Roger"
operator:
name = "Roger"
name += " is a good dog"
class constructor:
str(8) #"8"
32
print("Roger is " + str(8) + " years old") #Roger is
print("""Roger is
years old
""")
print('''
Roger is
years old
''')
33
startsswith() to check if the string starts with a
specific substring
endswith() to check if the string ends with a
specific substring
replace() to replace a part of a string
split() to split a string on a specific character
separator
strip() to trim the whitespace from a string
join() to append new letters to a string
find() to find the position of a substring
name = "Roger"
print(name.lower()) #"roger"
print(name) #"Roger"
name = "Roger"
print(len(name)) #5
name = "Roger"
print("ger" in name) #True
34
Escaping is a way to add special characters into a
string.
name = "Roger"
name = "Ro\"ger"
name = "Roger"
name[0] #'R'
name[1] #'o'
name[2] #'g'
name = "Roger"
name[-1] #"r"
35
You can also use a range, using what we call slicing:
name = "Roger"
name[0:2] #"Ro"
name[:2] #"Ro"
name[2:] #"ger"
36
Booleans
Python provides the bool type, which can have two
values: True and False (capitalized)
done = False
done = True
done = True
if done:
# run some code here
else:
# run some other code
done = True
type(done) == bool #True
37
Or using isinstance() , passing 2 arguments: the
variable, and the bool class:
done = True
isinstance(done, bool) #True
book_1_read = True
book_2_read = False
ingredients_purchased = True
meal_cooked = False
38
Numbers
Numbers in Python can be of 3 types: int , float
and complex .
Integer numbers
Integer numbers are represented using the int
age = 8
age = int(8)
fraction = 0.1
39
fraction = float(0.1)
Complex numbers
Complex numbers are of type complex .
complexNumber = 2+3j
complexNumber = complex(2, 3)
Once you have a complex number, you can get its real
and imaginary part:
complexNumber.real #2.0
complexNumber.imag #3.0
40
You can perform arithmetic operations on numbers,
using the arithmetic operators: + , - , * , /
1 + 1 #2
2 - 1 #1
2 * 2 #4
4 / 2 #2
4 % 3 #1
4 ** 2 #16
4 // 2 #2
+=
-=
*=
/=
%=
..and so on
age = 8
age += 1
Built-in Functions
There are 2 built-in functions that help with numbers:
41
round(0.12) #0
round(0.12, 1) #0.1
42
Constants
Python has no way to enforce a variable to be a
constant.
class Constants(Enum):
WIDTH = 1024
HEIGHT = 256
WIDTH = 1024
43
Enums
Enums are readable names that are bound to a
constant value.
class State(Enum):
INACTIVE = 0
ACTIVE = 1
print(State.ACTIVE)
44
list(State) # [<State.INACTIVE: 0>, <State.ACTIVE: 1
len(State) # 2
45
User Input
In a Python command line application you can display
information to the user using the print() function:
name = "Roger"
print(name)
46
Control statements
What's interesting to do with booleans, and
expressions that return a boolean in particular, is that
we can make decisions and take different roads
depending on their True or False value.
condition = True
if condition == True:
# do something
condition = True
if condition == True:
print("The condition")
print("was true")
47
condition = True
if condition == True:
print("The condition")
print("was true")
condition = True
if condition == True:
print("The condition")
print("was True")
else:
print("The condition")
print("was False")
condition = True
name = "Roger"
if condition == True:
print("The condition")
print("was True")
elif name == "Roger":
print("Hello Roger")
else:
print("The condition")
print("was False")
48
The second block in this case is executed if
condition is False , and the name variable value is
"Roger".
condition = True
name = "Roger"
if condition == True:
print("The condition")
print("was True")
elif name == "Roger":
print("Hello Roger")
elif name == "Syd":
print("Hello Syd")
elif name == "Flavio":
print("Hello Flavio")
else:
print("The condition")
print("was False")
Example:
a = 2
result = 2 if a == 0 else 3
print(result) # 3
49
Lists
Lists are an essential Python data structure.
For example:
items = []
items[0] # "Roger"
items[1] # 1
items[3] # True
50
Using the same notation you can change the value
stored at a specific index:
items[0] = "Roger"
items.index(0) # "Roger"
items.index(1) # 1
items[-1] # True
items[0:2] # ["Roger", 1]
items[2:] # ["Syd", True]
len(items) #4
method:
items.append("Test")
51
items.extend(["Test"])
items += ["Test"]
items.remove("Test")
#or
items.extend(["Test1", "Test2"])
52
To add multiple items at a specific index, you need to
use slices:
items.sort()
Tip: sort() will only work if the list holds values that
can be compared. Strings and integers for
example can't be compared, and you'll get an
error like TypeError: '<' not supported between
items.sort(key=str.lower)
instead.
itemscopy = items[:]
print(sorted(items, key=str.lower))
53
54
Tuples
Tuples are another fundamental Python data structure.
names[0] # "Roger"
names[1] # "Syd"
names.index('Roger') # 0
names.index('Syd') # 1
names[-1] # True
function:
55
len(names) # 2
len(names) #2
sorted(names)
56
Dictionaries
Dictionaries are a very important Python data
structure.
dog['name'] # 'Roger'
dog['age'] # 8
dog['name'] = 'Syd'
57
And another way is using the get() method, which
has an option to add a default value:
dog.get('name') # 'Roger'
dog.get('test', 'default') # 'default'
dog.pop('name') # 'Roger'
dog.popitem()
constructor:
58
print(list(dog.values()))
# ['Roger', 8]
print(list(dog.items()))
# [('name', 'Roger'), ('age', 8)]
len(dog) #2
dogCopy = dog.copy()
59
Sets
Sets are another important Python data structure.
We can say they work like tuples, but they are not
ordered, and they are mutable. Or we can say they
work like dictionaries, but they don't have keys.
60
set1 = {"Roger", "Syd"}
set2 = {"Roger"}
global function:
61
Functions
A function lets us create a set of instructions that we
can run when needed.
def hello():
print('Hello!')
hello()
62
def hello(name):
print('Hello ' + name + '!')
hello('Roger')
hello()
#Hello my friend!
hello('Roger', 8)
63
Parameters are passed by reference. All types in
Python are objects but some of them are immutable,
including integers, booleans, floats, strings, and
tuples. This means that if you pass them as
parameters and you modify their value inside the
function, the new value is not reflected outside of the
function:
def change(value):
value = 2
val = 1
change(val)
print(val) #1
def hello(name):
print('Hello ' + name + '!')
return name
def hello(name):
print('Hello ' + name + '!')
return
64
We can have the return statement inside a conditional,
which is a common way to end a function if a starting
condition is not met:
def hello(name):
if not name:
return
print('Hello ' + name + '!')
def hello(name):
print('Hello ' + name + '!')
return name, 'Roger', 8
65
Objects
Everything in Python is an object.
age = 8
print(age.real) # 8
print(age.imag) # 0
print(age.bit_length()) #4
items = [1, 2]
items.append(3)
items.pop()
66
The methods depend on the type of value.
id(age) # 140170065725376
age = 8
print(id(age)) # 140535918671808
age = 9
print(id(age)) # 140535918671840
items = [1, 2]
print(id(items)) # 140093713593920
items.append(3)
print(items) # [1, 2, 3]
print(id(items)) # 140093713593920
67
The address only changes if you reassign a variable to
another value.
age = 8
age = age + 1
#or
age += 1
and you check with id(age) you will find that age
68
Loops
Loops are one essential part of programming.
while loops
while loops are defined using the while keyword,
and they repeat their block until the condition is
evaluated as False :
condition = True
while condition == True:
print("The condition is True")
condition = True
while condition == True:
print("The condition is True")
condition = False
69
It's common to have a counter to stop the iteration
after some number of cycles:
count = 0
while count < 10:
print("The condition is True")
count = count + 1
for loops
Using for loops we can tell Python to execute a
block for a pre-determined amount of times, up front,
and without the need of a separate variable and
conditional to check its value.
items = [1, 2, 3, 4]
for item in items:
print(item)
70
items = [1, 2, 3, 4]
for index, item in enumerate(items):
print(index, item)
items = [1, 2, 3, 4]
for item in items:
if item == 2:
continue
print(item)
items = [1, 2, 3, 4]
for item in items:
if item == 2:
break
print(item)
71
Classes
Defining new objects in Python using
classes
class <class_name>:
# my class
class Dog:
# the Dog class
class Dog:
# the Dog class
def bark(self):
print('WOF!')
72
We create an instance of a class, an object, using this
syntax:
roger = Dog()
If you run
print(type(roger))
class Dog:
# the Dog class
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print('WOF!')
roger = Dog('Roger', 8)
print(roger.name) # 'Roger'
print(roger.age) # 8
roger.bark() # 'WOF!'
73
We can create an Animal class with a method
walk() :
class Animal:
def walk(self):
print('Walking..')
class Dog(Animal):
def bark(self):
print('WOF!')
roger = Dog()
roger.walk() # 'Walking..'
roger.bark() # 'WOF!'
74
Modules
Every Python file is a module.
def bark():
print('WOF!')
import dog
dog.bark()
bark()
75
The second strategy lets us pick the things we need.
Now you can choose, you can import dog from lib :
dog.bark()
bark()
76
The Python Standard
Library
Python exposes a lot of built-in functionality through its
standard library.
77
import math
math.sqrt(4) # 2.0
or
sqrt(4) # 2.0
78
The PEP8 Python style
guide
When you write code, you should adhere to the
conventions of the programming language you use.
79
Functions, variable names and file names are
lowercase, with underscores between words
(snake_case)
Class names are capitalized, separate words are
written with the capital letter too, (CamelCase)
Package names are lowercase and do not have
underscores between words
Variables that should not change (constants) are
written in uppercase
Variable names should be meaningful
Add useful comments, but avoid obvious
comments
Add spaces around operators
Do not use unnecessary whitespace
Add a blank line before a function
Add a blank line between methods in a class
Inside functions/methods, blank lines can be used
to separate related blocks of code to help
readability
80
Debugging
Debugging is one of the best skills you can learn, as it
will help you in many difficult situations.
breakpoint()
You can press n to step to the next line in the current
function. If the code calls functions, the debugger does
not get into them, and consider them "black boxes".
You can press s to step to the next line in the current
function. If the next line is a function, the debugger
goes into that, and you can then run one instruction of
that function at a time.
81
You can press q to stop the execution of the
program.
82
Variables scope
When you declare a variable, that variable is visible in
parts of your program, depending on where you
declare it.
age = 8
def test():
print(age)
print(age) # 8
test() # 8
def test():
age = 8
print(age)
test() # 8
print(age)
# NameError: name 'age' is not defined
83
Accept arguments from
the command line
Python offers several ways to handle arguments
passed when we invoke the program from the
command line.
python <filename>.py
list:
import sys
print(len(sys.argv))
print(sys.argv)
84
This is a simple way, but you have to do a lot of work.
You need to validate arguments, make sure their type
is correct, you need to print feedback to the user if
they are not using the program correctly.
import argparse
parser = argparse.ArgumentParser(
description='This program prints the name of my
)
import argparse
parser = argparse.ArgumentParser(
description='This program prints a color HEX val
)
args = parser.parse_args()
print(args.color) # 'red'
85
➜ python python program.py
usage: program.py [-h] -c color
program.py: error: the following arguments are requi
86
Lambda functions
Lambda functions (also called anonymous functions)
are tiny functions that have no name and only have
one expression as their body.
lambda a, b : a * b
multiply = lambda a, b : a * b
print(multiply(2, 2)) # 4
87
The utility of lambda functions comes when combined
with other Python functionality, for example in
combination with map() , filter() and reduce() .
88
Recursion
A function in Python can call itself. That's what
recursion is. And it can be pretty useful in many
scenarios.
3! = 3 * 2 * 1 = 6
4! = 4 * 3 * 2 * 1 = 24
5! = 5 * 4 * 3 * 2 * 1 = 120
def factorial(n):
if n == 1: return 1
return n * factorial(n-1)
print(factorial(3)) # 6
print(factorial(4)) # 24
print(factorial(5)) # 120
89
Recursion is helpful in many places, and it helps us
simplify our code when there's no other optimal way to
do it, so it's good to know this technique.
90
Nested functions
Functions in Python can be nested inside other
functions.
Here is an example:
def talk(phrase):
def say(word):
print(word)
91
def count():
count = 0
def increment():
nonlocal count
count = count + 1
print(count)
increment()
count()
92
Closures
If you return a nested function from a function, that
nested function has access to the variables defined in
that function, even if that function is not active any
more.
def counter():
count = 0
def increment():
nonlocal count
count = count + 1
return count
return increment
increment = counter()
print(increment()) # 1
print(increment()) # 2
print(increment()) # 3
93
Decorators
Decorators are a way to change, enhance or alter in
any way how a function works.
Example:
@logtime
def hello():
print('hello!')
def logtime(func):
def wrapper():
# do something before
val = func()
# do something after
return val
return wrapper
94
Docstrings
Documentation is hugely important, not just to
communicate to other people what is the goal of a
function/class/method/module, but also to yourself.
# this is a comment
def increment(n):
"""Increment a number"""
return n + 1
95
class Dog:
"""A class representing a dog"""
def __init__(self, name, age):
"""Initialize a new dog"""
self.name = name
self.age = age
def bark(self):
"""Let the dog bark"""
print('WOF!')
"""Dog module
This module does ... bla bla bla and provides the fo
- Dog
...
"""
class Dog:
"""A class representing a dog"""
def __init__(self, name, age):
"""Initialize a new dog"""
self.name = name
self.age = age
def bark(self):
"""Let the dog bark"""
print('WOF!')
96
def increment(n):
"""Increment
a number
"""
return n + 1
increment(n)
Increment
a number
97
Introspection
Functions, variables and objects can be analyzed
using introspection.
def increment(n):
return n + 1
print(increment)
or an object:
class Dog():
def bark(self):
print('WOF!')
roger = Dog()
print(roger)
98
print(type(increment))
# <class 'function'>
print(type(roger))
# <class '__main__.Dog'>
print(type(1))
# <class 'int'>
print(type('test'))
# <class 'str'>
print(dir(roger))
print(id(roger)) # 140227518093024
print(id(1)) # 140227521172384
99
Annotations
Python is dynamically typed. We do not have to
specify the type of a variable or function parameter, or
a function return value.
def increment(n):
return n + 1
count: int = 0
100
Exceptions
It's important to have a way to handle errors.
try:
# some lines of code
try:
# some lines of code
except <ERROR1>:
# handler <ERROR1>
except <ERROR2>:
# handler <ERROR2>
try:
# some lines of code
except <ERROR1>:
# handler <ERROR1>
except:
# catch all other exceptions
101
try:
# some lines of code
except <ERROR1>:
# handler <ERROR1>
except <ERROR2>:
# handler <ERROR2>
else:
# no exceptions were raised, the code ran succes
try:
# some lines of code
except <ERROR1>:
# handler <ERROR1>
except <ERROR2>:
# handler <ERROR2>
else:
# no exceptions were raised, the code ran succes
finally:
# do something in any case
result = 2 / 0
print(result)
102
Traceback (most recent call last):
File "main.py", line 1, in <module>
result = 2 / 0
ZeroDivisionError: division by zero
try:
result = 2 / 0
except ZeroDivisionError:
print('Cannot divide by zero!')
finally:
result = 1
print(result) # 1
try:
raise Exception('An error occurred!')
except Exception as error:
print(error)
103
class DogNotFoundException(Exception):
pass
try:
raise DogNotFoundException()
except DogNotFoundException:
print('Dog not found!')
104
The with statement
The with statement is very helpful to simplify
working with exception handling.
Instead of writing:
filename = '/Users/flavio/test.txt'
try:
file = open(filename, 'r')
content = file.read()
print(content)
finally:
file.close()
filename = '/Users/flavio/test.txt'
105
Installing 3rd party
packages using pip
The Python standard library contains a huge number
of utilities that simplify our Python development needs,
but nothing can satisfy everything.
106
pip install requests
and once you do, it will be available for all your Python
scripts, because packages are installed globally.
107
List comprehensions
List comprehensions are a way to create lists in a very
concise way.
numbers = [1, 2, 3, 4, 5]
numbers_power_2 = []
for n in numbers:
numbers_power_2.append(n**2)
108
Polymorphism
Polymorphism generalizes a functionality so it can
work on different types. It's an important concept in
object-oriented programming.
class Dog:
def eat():
print('Eating dog food')
class Cat:
def eat():
print('Eating cat food')
animal1 = Dog()
animal2 = Cat()
animal1.eat()
animal2.eat()
109
Operator Overloading
Operator overloading is an advanced technique we
can use to make classes comparable and to make
them work with Python operators.
class Dog:
# the Dog class
def __init__(self, name, age):
self.name = name
self.age = age
roger = Dog('Roger', 8)
syd = Dog('Syd', 7)
class Dog:
# the Dog class
def __init__(self, name, age):
self.name = name
self.age = age
def __gt__(self, other):
return True if self.age > other.age else Fal
Now if you try running print(roger > syd) you will get
the result True .
110
__eq__() to check for equality
__lt__() to check if an object should be
considered lower than another with the <
operator
__le__() for lower or equal ( <= )
__ge__() for greater or equal ( >= )
__ne__() for not equal ( != )
111
Virtual Environments
It's common to have multiple Python applications
running on your system.
Then run
source .venv/bin/activate
112
➜ folder
to
(.venv) ➜ folder
113
Conclusion
Thanks a lot for reading this book.
114