The Python Handbook
The Python Handbook
The Python Handbook
Forum Donate
This book does not try to cover everything under the sun related to
https://www.freecodecamp.org/news/the-python-handbook/ 1/115
4/19/2021 The Python Handbook
Note: You can get a PDF, ePub and Mobi version of this Python
Handbook
Enjoy!
Summary
Introduction to Python
Python 2 vs Python 3
Python Basics
Operators in Python
Strings in Python
Booleans in Python
Numbers in Python
Constants in Python
Enums in Python
https://www.freecodecamp.org/news/the-python-handbook/ 2/115
4/19/2021 The Python Handbook
Tuples in Python
Learn to code — free 3,000-hour curriculum
Dictionaries in Python
Sets in Python
Functions in Python
Objects in Python
Loops in Python
Classes in Python
Modules in Python
Debugging in Python
Recursion in Python
Closures in Python
Decorators in Python
Docstrings in Python
Introspection in Python
Annotations in Python
Exceptions in Python
Conclusion
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.
Forum Donate
The ecosystem is huge. There seems to be a library for everything you
can imagine. Learn to code — free 3,000-hour curriculum
This has pros and cons. In particular, you write programs faster, but on
the other hand you have less help from the tools to prevent possible
bugs. This means that you will nd out about certain issues only by
executing the program at runtime.
https://www.freecodecamp.org/news/the-python-handbook/ 5/115
4/19/2021 The Python Handbook
Forum Donate
Starting with Python is very easy. All you need is to install the of cial
package from python.org, for Windows, macOS or Linux, and you're
ready to go.
If you are new to programming, in the following posts I will guide you
https://www.freecodecamp.org/news/the-python-handbook/ 6/115
4/19/2021 The Python Handbook
Lower level languages like C++ and Rust might be great for expert
programmers, but they're daunting to begin with, and they take a long
time to master.
https://www.freecodecamp.org/news/the-python-handbook/ 7/115
4/19/2021 The Python Handbook
Forum Donate
Make sure you follow the speci c instructions for your operating
system. On macOS you can nd a detailed guide on
https:// aviocopes.com/python-installation-macos/.
If you open your terminal and type python , you will see a screen like
this:
https://www.freecodecamp.org/news/the-python-handbook/ 8/115
4/19/2021 The Python Handbook
Forum Donate
Notice the >>> symbol, and the cursor after that. You can type any
Python code here, and press the enter key to run it.
name = "Flavio"
print(name)
https://www.freecodecamp.org/news/the-python-handbook/ 9/115
4/19/2021 The Python Handbook
Forum Donate
Note: in the REPL, you can also just type name , press the enter
key and you'll get the value back. But in a program, you are not
going to see any output if you do so - you need to use print()
instead.
You can access the same interactive prompt using the IDLE
application that's installed by Python automatically:
This might be more convenient for you because with the mouse you
https://www.freecodecamp.org/news/the-python-handbook/ 10/115
4/19/2021 The Python Handbook
can move around and copy/paste more easily than with the terminal. Donate
Forum
Learn to code — free 3,000-hour curriculum
Those are the basics that come with Python by default. However I
recommend that you install IPython, probably the best command line
REPL application you can nd.
Install it with
Make sure the pip binaries are in your path, then run ipython :
https://www.freecodecamp.org/news/the-python-handbook/ 11/115
4/19/2021 The Python Handbook
Forum Donate
ipython is another interface that lets you work with a Python REPL,
and provides some nice features like syntax highlighting, code
completion, and much more.
https://www.freecodecamp.org/news/the-python-handbook/ 12/115
4/19/2021 The Python Handbook
Forum Donate
In this case the program is executed as a whole, not one line at a time.
And that's typically how we run programs.
https://www.freecodecamp.org/news/the-python-handbook/ 13/115
4/19/2021 The Python Handbook
./program.py
This is especially useful when you write scripts that interact with the
terminal.
https://www.freecodecamp.org/news/the-python-handbook/ 14/115
4/19/2021 The Python Handbook
Forum Donate
https://www.freecodecamp.org/news/the-python-handbook/ 15/115
4/19/2021 The Python Handbook
Forum Donate
https://www.freecodecamp.org/news/the-python-handbook/ 16/115
4/19/2021 The Python Handbook
Forum Donate
https://www.freecodecamp.org/news/the-python-handbook/ 17/115
4/19/2021 The Python Handbook
Forum Donate
and many more. Just open the command palette (View -> Command
Palette, or Cmd-Shift-P) and type python to see all the Python-
related commands:
https://www.freecodecamp.org/news/the-python-handbook/ 18/115
4/19/2021 The Python Handbook
Forum Donate
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:
https://www.freecodecamp.org/news/the-python-handbook/ 19/115
4/19/2021 The Python Handbook
Forum Donate
https://www.freecodecamp.org/news/the-python-handbook/ 20/115
4/19/2021 The Python Handbook
Forum Donate
https://www.freecodecamp.org/news/the-python-handbook/ 21/115
4/19/2021 The Python Handbook
Forum Donate
Once you have some code, click "Run" to run it on the right side of the
window:
https://www.freecodecamp.org/news/the-python-handbook/ 22/115
4/19/2021 The Python Handbook
Forum Donate
Python 2 vs Python 3
One key topic we should address, right from the start, is the Python 2
vs Python 3 discussion.
Many programs are still written using Python 2, and organizations still
actively work on those, because the migration to Python 3 is not trivial
and it would require a lot of work to upgrade those programs. And
large and important migrations always introduce new bugs.
But new code, unless you have to adhere to rules set by your
organization that forces Python 2, should always be written in Python
3.
https://www.freecodecamp.org/news/the-python-handbook/ 23/115
4/19/2021 The Python Handbook
Forum Donate
This book focuses on Python 3.
Learn to code — free 3,000-hour curriculum
Python Basics
Variables in Python
We can create a new Python variable by assigning a value to a label,
using the = assignment operator.
In this example we assign a string with the value "Roger" to the name
label:
name = "Roger"
age = 8
name1
AGE
aGE
a11111
my_name
_name
https://www.freecodecamp.org/news/the-python-handbook/ 24/115
4/19/2021 The Python Handbook
Forum Donate
123
test!
name%
Other than that, anything is valid unless it's a Python keyword. There
are some keywords like for , if , while , import and more.
There's no need to memorize them, as Python will alert you if you use
one of those as a variable, and you will gradually recognize them as
part of the Python programming language syntax.
1 + 1
"Roger"
name = "Roger"
print(name)
https://www.freecodecamp.org/news/the-python-handbook/ 25/115
4/19/2021 The Python Handbook
Comments
In a Python program, everything after a hash mark is ignored, and
considered a comment:
Indentation in Python
Indentation in Python is meaningful.
name = "Flavio"
print(name)
In this case, if you try to run this program you would get a Indentation
https://www.freecodecamp.org/news/the-python-handbook/ 26/115
4/19/2021 The Python Handbook
name = "Roger"
You can check the type of a variable by using the type() function,
passing the variable as an argument, and then comparing the result to
str :
name = "Roger"
type(name) == str #True
Or using isinstance() :
name = "Roger"
isinstance(name, str) #True
https://www.freecodecamp.org/news/the-python-handbook/ 27/115
4/19/2021 The Python Handbook
Forum Donate
Notice that to see the True value in Python, outside of a REPL, you
Learn to code — free 3,000-hour curriculum
need to wrap this code inside print() , but for clarity I avoid using
it.
We used the str class here, but the same works for other data types.
age = 1
type(age) == int #True
fraction = 0.1
type(fraction) == float #True
You saw how to create a type from a value literal, like this:
name = "Flavio"
age = 20
You can also create a variable of a speci c type by using the class
constructor, passing a value literal or a variable name:
https://www.freecodecamp.org/news/the-python-handbook/ 28/115
4/19/2021 The Python Handbook
name = str("Flavio")
anotherName = str(name)
Forum Donate
You can also convert from one type to another by using the class
constructor. Python will try to determine the correct value, for
example extracting a number from a string:
age = int("20")
print(age) #20
fraction = 0.1
intFraction = int(fraction)
print(intFraction) #0
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() wi
th base 10: 'test' error.
Those are just the basics of types. We have a lot more types in Python:
https://www.freecodecamp.org/news/the-python-handbook/ 29/115
4/19/2021 The Python Handbook
Operators in Python
Python operators are symbols that we use to run operations upon
values and variables.
assignment operator
arithmetic operators
comparison operators
logical operators
bitwise operators
age = 8
age = 8
anotherVariable = age
https://www.freecodecamp.org/news/the-python-handbook/ 30/115
4/19/2021 The Python Handbook
Forum Donate
1 + 1 #2
2 - 1 #1
2 * 2 #4
4 / 2 #2
4 % 3 #1
4 ** 2 #16
4 // 2 #2
Note that you don't need a space between the operands, but it's
good for readability.
print(-4) #-4
Forum Donate
+=
-=
*=
/=
%=
..and so on
Example:
age = 8
age += 1
# age is now 9
==
!=
>
<
>=
<=
https://www.freecodecamp.org/news/the-python-handbook/ 32/115
4/19/2021 The Python Handbook
Forum
You can use those operators to get a boolean value ( True or False ) Donate
depending on the result:
Learn to code — free 3,000-hour curriculum
a = 1
b = 2
a == b #False
a != b #True
a > b #False
a <= b #True
not
and
or
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
Forum Donate
or used in an expression returns the value of the rst operand that is
Learn to code — free 3,000-hour curriculum
not a falsy value ( False , 0 , '' , [] ..). Otherwise it returns the last
operand.
print(0 or 1) ## 1
print(False or 'hey') ## 'hey'
print('hi' or 'hey') ## 'hi'
print([] or False) ## 'False'
print(False or []) ## '[]'
and only evaluates the second argument if the rst one is true. So if
the rst argument is falsy ( False , 0 , '' , [] ..), it returns that
argument. Otherwise it evaluates the second argument:
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
https://www.freecodecamp.org/news/the-python-handbook/ 34/115
4/19/2021 The Python Handbook
^ performsLearn to code
a binary XOR— operation
free 3,000-hour curriculum
Bitwise operators are rarely used, only in very speci c situations, but
they are worth mentioning.
is and in in Python
is is called the identity operator. It is used to compare two objects
and returns true if both are the same object. More on objects later.
Let's say you have a function that compares an age variable to the 18
value, and returns True or False depending on the result.
Instead of writing:
def is_adult(age):
if age > 18:
return True
https://www.freecodecamp.org/news/the-python-handbook/ 35/115
4/19/2021 The Python Handbook
def is_adult(age):
return True if age > 18 else False
First you de ne the result if the condition is True, then you evaluate
the condition, then you de ne the result if the condition is false:
Strings in Python
A string in Python is a series of characters enclosed in quotes or
double quotes:
"Roger"
'Roger'
name = "Roger"
https://www.freecodecamp.org/news/the-python-handbook/ 36/115
4/19/2021 The Python Handbook
Forum Donate
You can concatenate two strings using the + operator:
Learn to code — free 3,000-hour curriculum
name = "Roger"
name += " is a good dog"
You can convert a number to a string using the str class constructor:
str(8) #"8"
print("""Roger is
https://www.freecodecamp.org/news/the-python-handbook/ 37/115
4/19/2021 The Python Handbook
Forum Donate
8
Learn to code — free 3,000-hour curriculum
years old
""")
print('''
Roger is
years old
''')
() t l
https://www.freecodecamp.org/news/the-python-handbook/ t f t i 38/115
4/19/2021 The Python Handbook
None of those methods alter the original string. They return a new,
modi ed string instead. For example:
name = "Roger"
print(name.lower()) #"roger"
print(name) #"Roger"
You can use some global functions to work with strings, too.
name = "Roger"
print(len(name)) #5
name = "Roger"
print("ger" in name) #True
https://www.freecodecamp.org/news/the-python-handbook/ 39/115
4/19/2021 The Python Handbook
Forum Donate
Escaping is a way to add special characters into a string.
Learn to code — free 3,000-hour curriculum
For example, how do you add a double quote into a string that's
wrapped into double quotes?
name = "Roger"
"Ro"Ger" will not work, as Python will think the string ends at "Ro" .
The way to go is to escape the double quote inside the string, with the
\ backslash character:
name = "Ro\"ger"
This applies to single quotes too \' , and for special formatting
characters like \t for tab, \n for new line and \\ for the backslash.
Given a string, you can get its characters using square brackets to get
a speci c item, given its index, starting from 0:
name = "Roger"
name[0] #'R'
name[1] #'o'
name[2] #'g'
https://www.freecodecamp.org/news/the-python-handbook/ 40/115
4/19/2021 The Python Handbook
Forum Donate
name = "Roger"
name[0:2] #"Ro"
name[:2] #"Ro"
name[2:] #"ger"
Booleans in Python
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
https://www.freecodecamp.org/news/the-python-handbook/ 41/115
4/19/2021 The Python Handbook
Forum Donate
When evaluating a value
Learn for—True
to code or False , if
free 3,000-hour the value is not a bool
curriculum
we have some rules depending on the type we're checking:
lists, tuples, sets, and dictionaries are False only when empty
done = True
type(done) == bool #True
done = True
isinstance(done, bool) #True
The global any() function is also very useful when working with
booleans, as it returns True if any of the values of the iterable (list, for
example) passed as argument are True :
book_1_read = True
book_2_read = False
https://www.freecodecamp.org/news/the-python-handbook/ 42/115
4/19/2021 The Python Handbook
Forum Donate
The global all() function
Learn to codeis—same, but returns
free 3,000-hour True if all of the
curriculum
values passed to it are True :
ingredients_purchased = True
meal_cooked = False
Numbers in Python
Numbers in Python can be of 3 types: int , float and complex .
age = 8
age = int(8)
To check if a variable is of type int , you can use the type() global
function:
https://www.freecodecamp.org/news/the-python-handbook/ 43/115
4/19/2021 The Python Handbook
Forum Donate
type(age) == int #True
Learn to code — free 3,000-hour curriculum
fraction = 0.1
fraction = float(0.1)
To check if a variable is of type float , you can use the type() global
function:
https://www.freecodecamp.org/news/the-python-handbook/ 44/115
4/19/2021 The Python Handbook
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
Again, to check if a variable is of type complex , you can use the type
() global function:
1 + 1 #2
https://www.freecodecamp.org/news/the-python-handbook/ 45/115
4/19/2021 The Python Handbook
2 - 1 #1
Forum Donate
2 * 2 #4
4 / 2 #2 Learn to code — free 3,000-hour curriculum
4 % 3 #1
4 ** 2 #16
4 // 2 #2
+=
-=
*=
/=
%=
..and so on
age = 8
age += 1
https://www.freecodecamp.org/news/the-python-handbook/ 46/115
4/19/2021 The Python Handbook
Forum Donate
round(0.12) #0Learn to code — free 3,000-hour curriculum
round(0.12, 1) #0.1
Several other math utility functions and constants are provided by the
Python standard library:
Constants in Python
Python has no way to enforce that a variable should be a constant.
https://www.freecodecamp.org/news/the-python-handbook/ 47/115
4/19/2021 The Python Handbook
Forum Donate
class Constants(Enum):
Learn to code — free 3,000-hour curriculum
WIDTH = 1024
HEIGHT = 256
WIDTH = 1024
No one will prevent you from overwriting this value, and Python will
not stop it.
That's what most Python code does that you will see.
Enums in Python
Enums are readable names that are bound to a constant value.
To use enums, import Enum from the enum standard library module:
Forum Donate
print(State.ACTIVE)
The same value can be reached by the number assigned in the enum:
print(State(1)) will return State.ACTIVE . Same for using the
square brackets notation State['ACTIVE'] .
https://www.freecodecamp.org/news/the-python-handbook/ 49/115
4/19/2021 The Python Handbook
name = "Roger"
print(name)
This approach gets input at runtime, meaning the program will stop
execution and will wait until the user types something and presses the
enter key.
You can also do more complex input processing and accept input at
program invocation time, and we'll see how to do that later on.
Learn to
boolean in particular, code
we can—make
free 3,000-hour curriculum
decisions and take different roads
depending on their True or False values.
In Python we do so using the if statement:
condition = True
if condition == True:
# do something
When the condition test resolves to True , like in the above case, its
block gets executed.
condition = True
if condition == True:
print("The condition")
print("was true")
The block can be formed by a single line, or multiple lines as well, and
it ends when you move back to the previous indentation level:
condition = True
if condition == True:
print("The condition")
print("was true")
https://www.freecodecamp.org/news/the-python-handbook/ 51/115
4/19/2021 The Python Handbook
condition = True
if condition == True:
print("The condition")
print("was True")
else:
print("The condition")
print("was False")
And you can have different linked if checks with elif that's
executed if the previous check 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")
https://www.freecodecamp.org/news/the-python-handbook/ 52/115
4/19/2021 The Python Handbook
In a if statement you can have just one if and else check, but
Forum Donate
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")
if and else can also be used in an inline format, which lets us return
one value or another based on a condition.
Example:
a = 2
result = 2 if a == 0 else 3
print(result) # 3
Lists in Python
Lists are an essential Python data structure.
The allow you to group together multiple values and reference them
all with a common name
https://www.freecodecamp.org/news/the-python-handbook/ 53/115
4/19/2021 The Python Handbook
all with a common name.
Forum Donate
items = []
You can reference the items in a list by their index, starting from zero:
items[0] # "Roger"
items[1] # 1
items[3] # True
https://www.freecodecamp.org/news/the-python-handbook/ 54/115
4/19/2021 The Python Handbook
Forum Donate
items[0] = "Roger"
items.index(0) # "Roger"
items.index(1) # 1
As with strings, using a negative index will start searching from the
end:
items[-1] # True
items[0:2] # ["Roger", 1]
items[2:] # ["Syd", True]
Get the number of items contained in a list using the len() global
function, the same we used to get the length of a string:
https://www.freecodecamp.org/news/the-python-handbook/ 55/115
4/19/2021 The Python Handbook
len(items) #4
Forum Donate
You can add items to the list by using a list append() method:
items.append("Test")
items.extend(["Test"])
items += ["Test"]
items.remove("Test")
https://www.freecodecamp.org/news/the-python-handbook/ 56/115
4/19/2021 The Python Handbook
Forum Donate
Learn to
You can add multiple code — free
elements 3,000-hour curriculum
using
#or
items.extend(["Test1", "Test2"])
To add an item in the middle of a list, at a speci c index, use the inser
t() method:
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
https://www.freecodecamp.org/news/the-python-handbook/ 57/115
4/19/2021
p g g f The Python Handbook
p p ,
Forum Donate
items.sort(key=str.lower)
instead.
Sorting modi es the original list content. To avoid that, you can copy
the list content using
itemscopy = items[:]
print(sorted(items, key=str.lower))
that will return a new list, sorted, instead of modifying the original list.
Tuples in Python
Tuples are another fundamental Python data structure.
that once a tuple is created, it can't be modi ed. You can't add or
Forum Donate
A tuple is ordered, like a list, so you can get its values by referencing
an index value:
names[0] # "Roger"
names[1] # "Syd"
names.index('Roger') # 0
names.index('Syd') # 1
As with strings and lists, using a negative index will start searching
from the end:
names[-1] # True
You can count the items in a tuple with the len() function:
https://www.freecodecamp.org/news/the-python-handbook/ 59/115
4/19/2021 The Python Handbook
Forum Donate
Get the number of items in a tuple using the len() global function,
the same we used to get the length of a string:
len(names) #2
You can create a sorted version of a tuple using the sorted() global
function:
sorted(names)
You can create a new tuple from existing tuples using the + operator:
https://www.freecodecamp.org/news/the-python-handbook/ 60/115
4/19/2021
ou ca c eate a e tup e o e ThestPython Handbook
g tup es us g t e ope ato :
Forum Donate
Dictionaries in Python
Dictionaries are a very important Python data structure.
The key can be any immutable value like a string, a number or a tuple.
The value can be anything you want.
dog['name'] # 'Roger'
dog['age'] # 8
https://www.freecodecamp.org/news/the-python-handbook/ 61/115
4/19/2021 The Python Handbook
Forum Donate
dog['name'] = 'Syd'
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'
The popitem() method retrieves and removes the last key/value pair
inserted into the dictionary:
dog.popitem()
Forum Donate
Get a list with the keys in a dictionary using the keys() method,
passing its result to the list() constructor:
Get the values using the values() method, and the key/value pairs
tuples using the items() method:
print(list(dog.values()))
# ['Roger', 8]
print(list(dog.items()))
# [('name', 'Roger'), ('age', 8)]
Get a dictionary length using the len() global function, the same we
used to get the length of a string or the items in a list:
len(dog) #2
You can add a new key/value pair to the dictionary in this way:
https://www.freecodecamp.org/news/the-python-handbook/ 63/115
4/19/2021 The Python Handbook
dog['favorite food'] = 'Meat'
Forum Donate
You can remove a key/value pair from a dictionary using the del
statement:
dogCopy = dog.copy()
Sets in Python
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.
https://www.freecodecamp.org/news/the-python-handbook/ 64/115
4/19/2021 The Python Handbook
Forum
Sets work well when you think about them as mathematical sets. Donate
You can count the items in a set with the len() global function:
You can get a list from the items in a set by passing the set to the list
() constructor:
Functions in Python
A function lets us create a set of instructions that we can run when
needed.
def hello():
print('Hello!')
This is the function de nition. Thereis a name ( hello ) and a body, the
set of instructions, which is the part that follows the colon. It's
indented one level on the right.
To run this function, we must call it. This is the syntax to call the
function:
hello()
def hello(name):
print('Hello ' + name + '!')
https://www.freecodecamp.org/news/the-python-handbook/ 67/115
4/19/2021 The Python Handbook
hello('Roger')
hello()
#Hello my friend!
hello('Roger', 8)
https://www.freecodecamp.org/news/the-python-handbook/ 68/115
4/19/2021 The Python Handbook
Forum Donate
Parameters are passed by reference. All types in Python are objects,
Learn to code — free 3,000-hour curriculum
def change(value):
value = 2
val = 1
change(val)
print(val) #1
If you pass an object that's not immutable, and you change one of its
properties, the change will be re ected outside.
def hello(name):
print('Hello ' + name + '!')
return name
When the function meets the return statement, the function ends.
def hello(name):
https://www.freecodecamp.org/news/the-python-handbook/ 69/115
4/19/2021 The Python Handbook
( )
print('Hello ' + name + '!') Forum Donate
return
Learn to code — free 3,000-hour curriculum
def hello(name):
if not name:
return
print('Hello ' + name + '!')
def hello(name):
print('Hello ' + name + '!')
return name, 'Roger', 8
Objects in Python
Everything in Python is an object.
Even values of basic primitive types (integer, string, oat..) are objects.
Li t bj t t
https://www.freecodecamp.org/news/the-python-handbook/ l di ti i thi 70/115
4/19/2021 The Python Handbook
Lists are objects, as are tuples, dictionaries, everything.
Forum Donate
Learn to code
Objects have attributes and— free 3,000-hour
methods that cancurriculum
be accessed using the
dot syntax.
age = 8
age now has access to the properties and methods de ned for all in
t objects.
This includes, for example, access to the real and imaginary part of
that number:
print(age.real) # 8
print(age.imag) # 0
print(age.bit_length()) #4
items = [1, 2]
items.append(3)
items.pop()
id(age) # 140170065725376
If you assign a different value to the variable, its address will change,
because the content of the variable has been replaced with another
value stored in another location in memory:
age = 8
print(id(age)) # 140535918671808
age = 9
print(id(age)) # 140535918671840
But if you modify the object using its methods, the address stays the
same:
items = [1, 2]
print(id(items)) # 140093713593920
items.append(3)
print(items) # [1 2 3]
https://www.freecodecamp.org/news/the-python-handbook/ 72/115
4/19/2021 The Python Handbook
print(items) # [1, 2, 3]
print(id(items)) # 140093713593920 Forum Donate
Some objects are mutable, while others are immutable. This depends
on the object itself.
age = 8
age = age + 1
#or
age += 1
and you check with id(age) , you will nd that age points to a
different memory location. The original value has not mutated, we just
switched to another value.
Loops in Python
Loops are one essential part of programming.
https://www.freecodecamp.org/news/the-python-handbook/ 73/115
4/19/2021 The Python Handbook
Forum Donate
while loops in Python
Learn
while loops are to code
de ned — free
using the 3,000-hour curriculum
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
In this case, the rst iteration is run, as the condition test is evaluated
to True . At the second iteration, the condition test evaluates to Fals
e , so the control goes to the next instruction after the loop.
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
https://www.freecodecamp.org/news/the-python-handbook/ 74/115
4/19/2021 The Python Handbook
Forum Donate
print("After the loop")
Learn to code — free 3,000-hour curriculum
items = [1, 2, 3, 4]
for item in items:
print(item)
Or, you can iterate a speci c amount of times using the range()
function:
To get the index, you should wrap the sequence into the enumerate()
function:
items = [1, 2, 3, 4]
f i d it i
https://www.freecodecamp.org/news/the-python-handbook/
t (it ) 75/115
4/19/2021 The Python Handbook
for index, item in enumerate(items):
print(index, item) Forum Donate
continue stops the current iteration and tells Python to execute the
next one.
break stops the loop altogether, and goes on with the next instruction
after the loop ends.
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)
Classes in Python
In addition to using the Python-provided types, we can declare our
https://www.freecodecamp.org/news/the-python-handbook/ 76/115
4/19/2021
g y p yp ,
The Python Handbook
class <class_name>:
# my class
class Dog:
# the Dog class
class Dog:
# the Dog class
def bark(self):
print('WOF!')
roger = Dog()
https://www.freecodecamp.org/news/the-python-handbook/ 77/115
4/19/2021 The Python Handbook
g g()
Forum Donate
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!'
https://www.freecodecamp.org/news/the-python-handbook/ 78/115
4/19/2021 The Python Handbook
Forum Donate
class Animal:
def walk(self):
print('Walking..')
class Dog(Animal):
def bark(self):
print('WOF!')
Now creating a new object of class Dog will have the walk() method
as that's inherited from Animal :
roger = Dog()
roger.walk() # 'Walking..'
roger.bark() # 'WOF!'
Modules in Python
Every Python le is a module.
You can import a module from other les, and that's the base of any
program of moderate complexity, as it promotes a sensible
https://www.freecodecamp.org/news/the-python-handbook/ 79/115
4/19/2021 The Python Handbook
program of moderate complexity, as it promotes a sensible
organization and code reuse. Forum Donate
In the typical Python program, one le acts as the entry point. The
other les are modules and expose functions that we can call from
other les.
def bark():
print('WOF!')
We can import this function from another le using import . And once
we do, we can reference the function using the dot notation, dog.bar
k() :
import dog
dog.bark()
Or, we can use the from .. import syntax and call the function
directly:
bark()
https://www.freecodecamp.org/news/the-python-handbook/ 80/115
4/19/2021 The Python Handbook
The second strategy lets us pick the things we need. Forum Donate
Now you can choose - you can import dog from lib :
dog.bark()
or you can reference the dog module speci c function importing from
lib.dog :
bark()
https://docs.python.org/3/library/index.html
Well that's the same with modules provided by the standard library:
import math
math.sqrt(4) # 2.0
https://www.freecodecamp.org/news/the-python-handbook/ 82/115
4/19/2021 The Python Handbook
Forum Donate
or Learn to code — free 3,000-hour curriculum
sqrt(4) # 2.0
If you learn the right naming and formatting conventions right from
the start, it will be easier to read code written by other people, and
people will nd your code easier to read.
Python de nes its conventions in the PEP8 style guide. PEP stands for
Python Enhancement Proposals and it's the place where all Python
language enhancements and discussions happen.
PEP8 is one of the rst ones, and one of the most important, too. It
de nes the formatting and also some rules on how to write Python in
a "pythonic" way.
Debugging in Python
D b i i f th b t kill
https://www.freecodecamp.org/news/the-python-handbook/ l it ill h l i 84/115
4/19/2021 The Python Handbook
Debugging is one of the best skills you can learn, as it will help you in
Forum Donate
many dif cult situations.
Learn to code — free 3,000-hour curriculum
Every language has its debugger. Python has pdb , available through
the standard library.
breakpoint()
You can type the name of any variable to inspect its value.
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
considers 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.
Forum Donate
Debugging is useful to evaluate the result of an instruction, and it's
especially goodLearn to code
to know how—to
free
use3,000-hour curriculum
it when you have complex
iterations or algorithms that you want to x.
age = 8
def test():
print(age)
print(age) # 8
test() # 8
def test():
age = 8
print(age)
test() # 8
i t( )
https://www.freecodecamp.org/news/the-python-handbook/ 86/115
4/19/2021 The Python Handbook
print(age)
# NameError: name 'age' is not defined Forum Donate
python <filename>.py
You can pass additional arguments and options when you do so, like
this:
A basic way to handle those arguments is to use the sys module from
the standard library.
import sys
print(len(sys.argv))
print(sys.argv)
https://www.freecodecamp.org/news/the-python-handbook/ 87/115
4/19/2021 The Python Handbook
Forum Donate
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, and 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 dogs'
)
import argparse
parser = argparse.ArgumentParser(
description='This program prints a color HEX value'
)
args = parser.parse_args()
https://www.freecodecamp.org/news/the-python-handbook/ 88/115
4/19/2021 The Python Handbook
Forum Donate
print(args.color) # 'red'
Learn to code — free 3,000-hour curriculum
You can set an option to have a speci c set of values, using choices :
that have no name and only have one expression as their body.
Forum Donate
lambda a, b : a * b
Lambda functions cannot be invoked directly, but you can assign them
to variables:
multiply = lambda a, b : a * b
print(multiply(2, 2)) # 4
https://www.freecodecamp.org/news/the-python-handbook/ 90/115
4/19/2021 The Python Handbook
Forum Donate
Learn to
The utility of lambda code — free
functions 3,000-hour
comes curriculumwith other
when combined
Python functionality, for example in combination with map() , filter
() and reduce() .
Recursion in Python
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
https://www.freecodecamp.org/news/the-python-handbook/ 91/115
4/19/2021 The Python Handbook
Forum
Donate
If inside the factorial() function you call factorial(n) instead of f
Learn to code — free 3,000-hour curriculum
This is useful to create utilities that are useful to a function, but not
useful outside of it.
Here is an example:
def talk(phrase):
def say(word):
print(word)
https://www.freecodecamp.org/news/the-python-handbook/ 92/115
4/19/2021 The Python Handbook
If you want to access a variable de ned in the outer function from the
inner function, you rst need to declare it as nonlocal :
def count():
count = 0
def increment():
nonlocal count
count = count + 1
print(count)
increment()
count()
Closures in Python
If you return a nested function from a function, that nested function
has access to the variables de ned in that function, even if that
function is not active any more.
def counter():
t 0
https://www.freecodecamp.org/news/the-python-handbook/ 93/115
4/19/2021 The Python Handbook
count = 0
Forum Donate
def increment():
Learn
nonlocal to code — free 3,000-hour curriculum
count
count = count + 1
return count
return increment
increment = counter()
print(increment()) # 1
print(increment()) # 2
print(increment()) # 3
We return the increment() inner function, and that still has access to
the state of the count variable even though the counter() function
has ended.
Decorators in Python
Decorators are a way to change, enhance, or alter in any way how a
function works.
Example:
@logtime
def hello():
print('hello!')
Forum Donate
Whenever we call hello() , the decorator is going to be called.
Learn to code — free 3,000-hour curriculum
def logtime(func):
def wrapper():
# do something before
val = func()
# do something after
return val
return wrapper
Docstrings in Python
Documentation is hugely important, not just to communicate to other
people what the goal of a function/class/method/module is, but it also
communicates it to yourself.
When you come back to your code 6 or 12 months from now, you
might not remember all the knowledge you are holding in your head.
At that point, reading your code and understanding what it is
supposed to do will be much more dif cult.
# this is a comment
https://www.freecodecamp.org/news/the-python-handbook/ 95/115
4/19/2021 The Python Handbook
Forum Donate
Another way is to use docstrings.
Learn to code — free 3,000-hour curriculum
def increment(n):
"""Increment a number"""
return n + 1
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 following classes:
https://www.freecodecamp.org/news/the-python-handbook/ 96/115
4/19/2021 The Python Handbook
- Dog
...
Forum Donate
"""
Learn to code — free 3,000-hour curriculum
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!')
def increment(n):
"""Increment
a number
"""
return n + 1
Python will process those and you can use the help() global function
to get the documentation for a class/method/function/module.
increment(n)
Increment
a number
https://www.freecodecamp.org/news/the-python-handbook/ 97/115
4/19/2021 The Python Handbook
Forum Donate
There are many different standards to format docstrings, and you can
Learn to code — free 3,000-hour curriculum
choose to adhere to your favorite one.
Introspection in Python
Functions, variables, and objects can be analyzed using introspection.
First, using the help() global function we can get the documentation
if provided in form of docstrings.
def increment(n):
return n + 1
print(increment)
or an object:
class Dog():
def bark(self):
i t('WOF!')
https://www.freecodecamp.org/news/the-python-handbook/ 98/115
4/19/2021 The Python Handbook
print('WOF!')
Forum Donate
roger = Dog()
Learn to code — free 3,000-hour curriculum
print(roger)
print(type(increment))
# <class 'function'>
print(type(roger))
# <class '__main__.Dog'>
print(type(1))
# <class 'int'>
print(type('test'))
# <class 'str'>
The dir() global function lets us nd out all the methods and
attributes of an object:
print(dir(roger))
https://www.freecodecamp.org/news/the-python-handbook/ 99/115
4/19/2021 The Python Handbook
Forum Donate
print(id(roger)) # 140227518093024
print(id(1))
Learn to code — free 3,000-hour curriculum
# 140227521172384
Annotations in Python
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
Forum Donate
count: int = 0
Learn to code — free 3,000-hour curriculum
Python will ignore those annotations. A separate tool called mypy can
be run standalone, or integrated by IDE like VS Code or PyCharm to
automatically check for type errors statically, while you are coding. It
will also help you catch type mismatch bugs before even running the
code.
A great help especially when your software becomes large and you
need to refactor your code.
Exceptions in Python
It's important to have a way to handle errors, and Python gives us
exception handling to do so.
try:
# some lines of code
If an error occurs, Python will alert you and you can determine which
kind of error occurred using a except blocks:
try:
# some lines of code
except <ERROR1>:
# handler <ERROR1>
https://www.freecodecamp.org/news/the-python-handbook/ 101/115
4/19/2021 The Python Handbook
except <ERROR2>:
# handler <ERROR2>
Forum Donate
To catch all exceptions you can use except without any error type:
try:
# some lines of code
except <ERROR1>:
# handler <ERROR1>
except:
# catch all other exceptions
try:
# some lines of code
except <ERROR1>:
# handler <ERROR1>
except <ERROR2>:
# handler <ERROR2>
else:
# no exceptions were raised, the code ran successfully
try:
# some lines of code
except <ERROR1>:
# handler <ERROR1>
except <ERROR2>:
# handler <ERROR2>
https://www.freecodecamp.org/news/the-python-handbook/ 102/115
4/19/2021 The Python Handbook
else:
Forum
# no exceptions were raised, the code ran successfully Donate
finally:
Learn to code — free 3,000-hour curriculum
# do something in any case
For example if you are reading a le, you might get an EOFError . If you
divide a number by zero you will get a ZeroDivisionError . If you have
a type conversion issue you might get a TypeError .
result = 2 / 0
print(result)
and the lines of code after the error will not be executed.
https://www.freecodecamp.org/news/the-python-handbook/ 103/115
4/19/2021 The Python Handbook
print(result) # 1
You can raise exceptions in your own code, too, using the raise
statement:
try:
raise Exception('An error occurred!')
except Exception as error:
print(error)
class DogNotFoundException(Exception):
pass
try:
raise DogNotFoundException()
except DogNotFoundException:
print('Dog not found!')
For example when working with les, each time we open a le, we
must remember to close it.
Instead of writing:
filename = '/Users/flavio/test.txt'
try:
file = open(filename, 'r')
content = file.read()
print(content)
finally:
file.close()
https://www.freecodecamp.org/news/the-python-handbook/ 105/115
4/19/2021 The Python Handbook
Learn to
with open(filename, code
'r') as — free 3,000-hour curriculum
file:
content = file.read()
print(content)
with is not just helpful to work with les. The above example is just
meant to introduce its capabilities.
Those modules are all collected in a single place, the Python Package
Index available at https://pypi.org, and they can be installed on your
system using pip .
There are more than 270,000 packages freely available at the time of
writing.
You should have pip already installed if you followed the Python
installation instructions.
or, if you do have troubles, you can also run it through python -m :
For example you can install the requests package, a popular HTTP
library:
and once you do, it will be available for all your Python scripts,
because packages are installed globally.
https://www.freecodecamp.org/news/the-python-handbook/ 107/115
4/19/2021 The Python Handbook
numbers = [1, 2, 3, 4, 5]
You can create a new list using a list comprehension, composed by the
numbers list elements, power 2:
https://www.freecodecamp.org/news/the-python-handbook/ 108/115
4/19/2021 The Python Handbook
Forum Donate
numbers_power_2 = [n**2 for n in numbers]
Learn
# [1, 4, 9, 16, 25] to code — free 3,000-hour curriculum
numbers_power_2 = []
for n in numbers:
numbers_power_2.append(n**2)
Polymorphism in Python
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():
https://www.freecodecamp.org/news/the-python-handbook/ 109/115
4/19/2021 The Python Handbook
()
print('Eating cat food') Forum Donate
Then we can generate objects and we can call the eat() method
regardless of the class the object belongs to, and we'll get different
results:
animal1 = Dog()
animal2 = Cat()
animal1.eat()
animal2.eat()
class Dog:
# the Dog class
def __init__(self, name, age):
self.name = name
self.age = age
https://www.freecodecamp.org/news/the-python-handbook/ 110/115
4/19/2021 The Python Handbook
Forum Donate
roger = Dog('Roger', 8)
Learn to code — free 3,000-hour curriculum
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 False
Now if you try running print(roger > syd) you will get the result Tr
ue .
https://www.freecodecamp.org/news/the-python-handbook/ 111/115
4/19/2021 The Python Handbook
There are a few more methods to work with other operators, but you
get the idea.
When applications require the same module, at some point you will
reach a tricky situation where an app needs a version of a module, and
another app a different version of that same module.
Forum Donate
Create a virtual environment using
Learn to code — free 3,000-hour curriculum
in the folder where you want to start the project, or where you
already have an existing project.
Then run
source .venv/bin/activate
➜ folder
to
(.venv) ➜ folder
Now running pip will use this virtual environment instead of the
global environment.
https://www.freecodecamp.org/news/the-python-handbook/ 113/115
4/19/2021 The Python Handbook
Forum Donate
Conclusion
Learn to code — free 3,000-hour curriculum
Thanks a lot for reading this book.
Note: You can get a PDF, ePub and Mobi version of this Python
Handbook
Flavio Copes
Read more posts by this author.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers,
Trending Guides
Our Nonpro t
About Alumni Network Open Source Shop Support Sponsors Academic Honesty