The Ultimate Python Beginner's Handbook
The Ultimate Python Beginner's Handbook
Forum Donate
This Python Guide for Beginners allows you to learn the core of the
language in a matter of hours instead of weeks.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 1/119
4/19/2021 The Ultimate Python Beginner's Handbook
Quick info: You can download a PDF version of this Python Guide forDonate
Forum
Beginners.
Learn to code — free 3,000-hour curriculum
Table of contents
1. Introduction to Python
2. Installing Python 3
3. Running Code
4. Syntax
5. Comments
6. Variables
7. Types
8. Typecasting
9. User Input
10. Operators
11. Conditionals
12. Lists
13. Tuples
14. Sets
15. Dictionaries
18. Functions
19. Scope
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 2/119
4/19/2021 The Ultimate Python Beginner's Handbook
22. Modules
24. Files
26. Inheritance
27. Exceptions
28. Conclusion
Introduction to Python
Python was created in 1990 by Guido van Rossum in Holland.
Python is:
Python has been growing a lot recently partly because of its many
uses in the following areas:
You can easily organize your code in modules and reuse them or share
them with others.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 4/119
4/19/2021 The Ultimate Python Beginner's Handbook
Installing Python 3
If you use a Mac or Linux you already have Python installed. But
Windows doesn't come with Python installed by default.
You also might have Python 2, and we are going to use Python 3. So
you should check to see if you have Python 3 rst.
python3 -V
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 5/119
4/19/2021 The Ultimate Python Beginner's Handbook
On the rst screen, check the box indicating to "Add Python 3.x to
PATH" and then click on "Install Now".
Wait for the installation process to nish until the next screen with
the message "Setup was successful".
Click on "Close".
xcode-select --install
brew update
brew install python3
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 6/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum
Homebrew already adds Python 3 to the PATH, so you don't have to Donate
do anything else.
Learn to code — free 3,000-hour curriculum
Running Code
You can run Python code directly in the terminal as commands or you
can save the code in a le with the .py extension and run the Python
le.
Terminal
Running commands directly in the terminal is recommended when
you want to run something simple.
Forum Donate
You should see something like this in your terminal indicating the
version (in my case, Python 3.6.9), the operating system (I'm using
Linux), and some basic commands to help you.
Let's test it by running our rst program to perform basic math and
add two numbers.
>>> 2 + 2
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 8/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
The alternative is simply to open a text editor, type the code, and save
the le with a .py extension.
print('Second Program')
The message goes inside the parentheses with either single quotes or
double quotes, both work the same.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 9/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
Second Program
Learn to code — free 3,000-hour curriculum
Syntax
Python is known for its clean syntax.
Semicolons
Python doesn't use semicolons to nish lines. A new line is enough to
tell the interpreter that a new command is beginning.
In this example, we have two commands that will display the messages
inside the single quotes.
print('First command')
print('Second command')
Output:
First command
Second command
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 10/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
But the following is wrong due to the semicolons in the end:
Learn to code — free 3,000-hour curriculum
print('First command');
print('Second command');
Indentation
Many languages use curly-brackets to de ne scope.
def my_function():
print('First command')
def my_function():
print('First command')
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 11/119
4/19/2021 The Ultimate Python Beginner's Handbook
Learn to code
Python is case sensitive. — free
So the 3,000-hour
variables namecurriculum
and Name are not the
same thing and store different values.
name = 'Renan'
Name = 'Moura'
As you can see, variables are easily created by just assigning values to
them using the = symbol.
Comments
Finally, to comment something in your code, use the hash mark # .
This was just an overview. The details of each of these will become
clearer in the next chapters with examples and broader explanations.
Comments
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 12/119
4/19/2021 The Ultimate Python Beginner's Handbook
But what if new people come on board your project after a year and
the project has 3 modules, each with 10,000 lines of code?
Think about people who don't know a thing about your app and who
are suddenly having to maintain it, x it, or add new features.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 13/119
4/19/2021 The Ultimate Python Beginner's Handbook
You can use a comment to explain what some piece of code does.
Forum Donate
Multiline Comments
Maybe you want to comment on something very complex or describe
how some process works in your code.
Variables
In any program, you need to store and manipulate data to create a
ow or some speci c logic.
You can have a variable to store a name, another one to store the age
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 14/119
4/19/2021 The Ultimate Python Beginner's Handbook
name='Bob'
age=32
You can use the print() function to show the value of a variable.
print(name)
print(age)
Bob
32
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 15/119
4/19/2021 The Ultimate Python Beginner's Handbook
If you need it, you can also re-declare a variable just by changing its
value.
Naming Conventions
Let's continue from the last section when I talked about meaning and
context.
Say you want to store the time of a party, just call it party_time .
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 16/119
4/19/2021 The Ultimate Python Beginner's Handbook
Remember, use names that you can recall inside your program easily.
Bad naming can cost you a lot of time and cause annoying bugs.
Are Case sensitive: time and TIME are not the same
Types
To store data in Python you need to use a variable. And every variable
has its type depending on the value of the data stored.
Python has dynamic typing, which means you don't have to explicitly
declare the type of your variable -- but if you want to, you can.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 17/119
4/19/2021 The Ultimate Python Beginner's Handbook
Lists, Tuples, Sets, and Dictionaries are all data types and have
Forum Donate
dedicated sections later on with more details, but we'll look at them
Learn to code — free 3,000-hour curriculum
brie y here.
This way I can show you the most important aspects and operations of
each one in their own section while keeping this section more concise
and focused on giving you a broad view of the main data types in
Python.
Just use the type() function and pass the variable of your choice as
an argument, like the example below.
print(type(my_variable))
Boolean
The boolean type is one of the most basic types of programming.
my_bool = True
print(type(my_bool))
my_bool = bool(1024)
print(type(my_bool))
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 18/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
<class 'bool'>
Learn to code — free 3,000-hour curriculum
<class 'bool'>
Numbers
There are three types of numeric types: int, oat, and complex.
Integer
my_int = 32
print(type(my_int))
my_int = int(32)
print(type(my_int))
<class 'int'>
<class 'int'>
Float
my_float = 32.85
print(type(my_float))
my_float = float(32.85)
print(type(my_float))
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 19/119
4/19/2021 The Ultimate Python Beginner's Handbook
<class 'float'>
Forum Donate
<class 'float'>
Learn to code — free 3,000-hour curriculum
Complex
my_complex_number = 32+4j
print(type(my_complex_number))
my_complex_number = complex(32+4j)
print(type(my_complex_number))
<class 'complex'>
<class 'complex'>
String
The text type is one of the most commons types out there and is often
called string or, in Python, just str .
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 20/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
Concatenation is when you have two or more strings and you want to
join them into one.
print(word1 + word2)
New York
The string type has many built-in methods that let us manipulate
them. I will demonstrate how some of these methods work.
print(len('New York'))
8
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 21/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
Old York
print('New York'.upper())
NEW YORK
The lower() method does the opposite, and returns all characters as
lowercase.
print('New York'.lower())
new york
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 22/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
Lists
A list has its items ordered and you can add the same item as many
times as you want. An important detail is that lists are mutable.
Mutability means you can change a list after its creation by adding
items, removing them, or even just changing their values. These
operations will be demonstrated later in the section dedicated to
Lists.
<class 'list'>
<class 'list'>
Tuples
A tuple is just like a list: ordered, and allows repetition of items.
Immutability means you can't change a tuple after its creation. If you
try to add an item or update one, for instance, the Python intepreter
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 23/119
4/19/2021 The Ultimate Python Beginner's Handbook
will show you an error. I will show that these errors occur later in the Donate
Forum
section dedicated to Tuples.
Learn to code — free 3,000-hour curriculum
<class 'tuple'>
<class 'tuple'>
Sets
Sets don't guarantee the order of the items and are not indexed.
A key point when using sets: they don't allow repetition of an item.
<class 'set'>
<class 'set'>
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 24/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum
Dictionaries
Donate
<class 'dict'>
<class 'dict'>
Typecasting
Typecasting allows you to convert between different types.
This way you can have an int turned into a str , or a float turned
into an int , for instance.
Explicit conversion
To cast a variable to a string just use the str() function.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 25/119
4/19/2021 The Ultimate Python Beginner's Handbook
# int to str
my_str = str(32)
print(my_str)
# float to str
my_str = str(32.0)
print(my_str)
32
32
32.0
# str to int
my_int = int('32')
print(my_int)
32
3
32
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 26/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
# int to float
my_float = float(32)
print(my_float)
# str to float
my_float = float('32')
print(my_float)
3.2
32.0
32.0
Implicit conversion
The example below shows implicit conversion when adding an int
and a float .
Notice that my_sum is float . Python uses float to avoid data loss
since the int type can not represent the decimal digits.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 27/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
print(my_sum)
print(type(my_sum))
35.2
<class 'float'>
On the other hand, in this example, when you add an int and a str ,
Python will not be able to make the implicit conversion, and the
explicit type conversion is necessary.
my_int = 32
my_str = '32'
64
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 28/119
4/19/2021 The Ultimate Python Beginner's Handbook
The same error is thrown when trying to add float and str types
without making an explicit conversion.
my_float = 3.2
my_str = '32'
35.2
User Input
If you need to interact with a user when running your program in the
command line (for example, to ask for a piece of information), you can
use the input() function.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 29/119
4/19/2021 The Ultimate Python Beginner's Handbook
print(country)
Forum Donate
Brazil
The captured value is always string . Just remember that you might
need to convert it using typecasting.
print(age)
print(type(age))
age = int(age)
print(type(age))
29
<class 'str'>
<class 'int'>
O t
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 30/119
Operators
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
In a programming language,
Learn operators
to code — are special
free 3,000-hour symbols that you
curriculum
can apply to your variables and values in order to perform operations
such as arithmetic/mathematical and comparison.
Python has lots of operators that you can apply to your variables and I
will demonstrate the most used ones.
Arithmetic Operators
Arithmetic operators are the most common type of operators and also
the most recognizable ones.
They are:
+ : Addition
- : Subtraction
* : Multiplication
/ : Division
** : Exponentiation
print('Addition:', 5 + 2)
print('Subtraction:', 5 - 2)
print('Multiplication:' 5 * 2)
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 31/119
4/19/2021 The Ultimate Python Beginner's Handbook
print( Multiplication: , 5 * 2)
print('Division:', 5 / 2) Forum Donate
print('Floor Division:', 5 // 2)
Learn to code
print('Exponentiation:', — free
5 ** 2) 3,000-hour curriculum
print('Modulus:', 5 % 2)
Addition: 7
Subtraction: 3
Multiplication: 10
Division: 2.5
Floor Division: 2
Exponentiation: 25
Modulus: 1
Concatenation
Concatenation is when you have two or more strings and you want to
join them into one.
This useful when you have information in multiple variables and want
to combine them.
For instance, in this next example I combine two variables that contain
my rst name and my last name respectively to have my full name.
Renan Moura
print(age)
Comparison Operators
Use comparison operators to compare two values.
They are:
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 33/119
4/19/2021 The Ultimate Python Beginner's Handbook
print('Equal:', 5 == 2)
print('Not equal:', 5 != 2)
print('Greater than:', 5 > 2)
print('Less than:', 5 < 2)
print('Greater than or equal to:', 5 >= 2)
print('Less than or equal to:', 5 <= 2)
Equal: False
Assignment Operators
As the name implies, these operators are used to assign values to
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 34/119
4/19/2021 The Ultimate Python Beginner's Handbook
The assignment operation takes the value on the right and assigns it to
the variable on the left.
= : simple assignment
x = 7
print(x)
x = 7
x += 2
print(x)
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 35/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
x = 7
x -= 2
print(x)
x = 7
x *= 2
print(x)
14
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 36/119
4/19/2021 The Ultimate Python Beginner's Handbook
x = 7
Forum Donate
x /= 2
Learn to code — free 3,000-hour curriculum
print(x)
3.5
x = 7
x %= 2
print(x)
x = 7
x //= 2
print(x)
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 37/119
4/19/2021 The Ultimate Python Beginner's Handbook
x = 7
x **= 2
print(x)
49
Logical Operators
Logical operators are used to combine statements applying boolean
algebra.
They are:
x = 5
y = 2
print(x == 5 or y > 3)
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 38/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
print(not (x == 5))
Learn to code — free 3,000-hour curriculum
False
True
False
Membership Operators
These operators provide an easy way to check if a certain object is
present in a sequence: string , list , tuple , set , and dictionary .
They are:
number_list = [1, 2, 4, 5, 6]
print( 1 in number_list)
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 39/119
4/19/2021 The Ultimate Python Beginner's Handbook
True
Conditionals
Conditionals are one of the cornerstones of any programming
language.
The if statement
The way you implement a conditional is through the if statement.
if expression:
statement
The expression contains some logic that returns a boolean, and the s
tatement is executed only if the return is True .
A simple example:
bob age = 32
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 40/119
4/19/2021 The Ultimate Python Beginner's Handbook
bob_age 32
sarah_age = 29 Forum Donate
We have two variables indicating the ages of Bob and Sarah. The
condition in plain English says "if Bob's age is greater than Sarah's age,
then print the phrase 'Bob is older than Sarah'".
Since the condition returns True , the phrase will be printed on the
console.
In this example, we swapped Bob's and Sarah's age. The rst condition
will return False since Sarah is older now, and then the program will
print the phrase after the else instead.
bob_age = 29
sarah_age = 32
bob_age = 32
sarah_age = 32
Once again we changed their ages and now both are 32 years old.
As such, the condition in the elif is met. Since both have the same
age the program will print "Bob and Sarah have the same age".
Notice you can have as many elif s as you want, just put them in
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 42/119
4/19/2021 The Ultimate Python Beginner's Handbook
bob_age = 32
sarah_age = 32
Nested conditionals
You might need to check more than one conditional for something to
happen.
For instance, the second phrase "Bob is the oldest" is printed only if
both if s pass.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 43/119
4/19/2021 The Ultimate Python Beginner's Handbook
bob_age = 32
Forum Donate
sarah_age = 28
mary_age = 25
Learn to code — free 3,000-hour curriculum
This way, your code is smaller, more readable and easier to maintain.
bob_age = 32
sarah_age = 28
mary_age = 25
Ternary Operators
The ternary operator is a one-line if statement.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 44/119
4/19/2021 The Ultimate Python Beginner's Handbook
a = 25
b = 50
x = 0
y = 1
print(result)
Here we use four variables, a and b are for the condition, while x
and y represent the expressions.
If the expression holds true, i.e., a is greater than b , then the value of
x will be attributed to result which will be equal to 0.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 45/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
However, if a is less than b , then we have the value of y assigned to
Learn to
result , and result code
will — free
hold 3,000-hour
the value 1 . curriculum
Since a is less than b , 25 < 50, result will have 1 as nal value
from y .
Lists
As promised in the Types section, this section and the next three
about Tuples, Sets, and Dictionaries will have more in depth
explanations of each of them since they are very important and
broadly used structures in Python to organize and deal with data.
A list has its items ordered and you can add the same item as many
times as you want.
Mutability means you can change a list after its creation by adding
items, removing them, or even just changing their values.
Initialization
Empty List
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 46/119
4/19/2021 The Ultimate Python Beginner's Handbook
Adding in a List
To add an item in the end of a list, use append() .
print(people)
To specify the position for the new item, use the insert() method.
print(people)
Updating in a List
Specify the position of the item to update and set the new value
['Bob', 'Sarah']
Deleting in a List
Use the remove() method to delete the item given as an argument.
['Mary']
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 48/119
4/19/2021 The Ultimate Python Beginner's Handbook
people = ['Bob', 'Mary']
people.clear() Forum Donate
Retrieving in a List
Use the index to reference the item.
Mary
if 'Bob' in people:
print('Bob exists!')
else:
print('There is no Bob!')
Tuples
A tuple is similar to a list: it's ordered, and allows repetition of items.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 49/119
4/19/2021 The Ultimate Python Beginner's Handbook
A tuple is similar to a list: it s ordered, and allows repetition of items.
Forum Donate
There is just one difference:
Learn a tuple
to code — is immutable.
free 3,000-hour curriculum
Initialization
Empty Tuple
people = ()
Adding in a Tuple
Tuples are immutable. This means that if you try to add an item, you
will see an error.
Updating in a Tuple
Updating an item will also return an error.
But there is a trick: you can convert into a list, change the item, and
then convert it back to a tuple.
('Bob', 'Sarah')
Deleting in a Tuple
For the same reason you can't add an item, you also can't delete an
item, since they are immutable.
Retrieving in a Tuple
Use the index to reference the item.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 51/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
if 'Bob' in people:
print('Bob exists!')
else:
print('There is no Bob!')
Sets
Sets don't guarantee the order of items and are not indexed.
A key point when using sets: they don't allow repetition of an item.
Initialization
Empty Set
people = set()
Adding in a Set
Use the add() method to add one item.
people.add('Sarah')
people.update(['Carol', 'Susan'])
people.add('Mary')
print(people)
{'Bob', 'Mary'}
Updating in a Set
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 53/119
4/19/2021 The Ultimate Python Beginner's Handbook
Items in a set are not mutable. You have to either add orForum
delete an Donate
item.
Learn to code — free 3,000-hour curriculum
Deleting in a Set
To remove Bob from the dictionary:
{'Mary'}
To delete everybody:
people.clear()
if 'Bob' in people:
print('Bob exists!')
else:
print('There is no Bob!')
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 54/119
4/19/2021 The Ultimate Python Beginner's Handbook
Initialization of a Dictionary
Empty Dictionary
people = {}
Adding in a Dictionary
If the key doesn't exist yet, it is appended to the dictionary.
people['Sarah']=32
Updating a Dictionary
If the key already exists, the value is just updated.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 55/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
#Bob's age is Learn
28 nowto code — free 3,000-hour curriculum
people['Bob']=28
Deleting in a Dictionary
To remove Bob from the dictionary:
people.pop('Bob')
To delete everybody:
people.clear()
Retrieving in a Dictionary
bob_age = people['Bob']
print(bob_age)
30
Forum
Dictionary Donate
if 'Bob' in people:
print('Bob exists!')
else:
print('There is no Bob!')
while Loops
Loops are used when you need to repeat a block of code a certain
number of times or apply the same logic over each item in a collection.
Basic Syntax
The basic syntax of a while loop is as below.
while condition:
statement
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
You can use any variable name, but I chose number because it makes
sense in the context. A common generic choice would be simply i .
If you don't do the incrementation you will have an in nite loop since
number will never reach a value greater than 5. This is a very
important detail!
else block
When the condition returns False , the else block will be called.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 58/119
4/19/2021 The Ultimate Python Beginner's Handbook
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
No numbers left!
Notice the phrase 'No numbers left!' is printed after the loop ends,
that is after the condition number <= 5 evaluates to False .
number = 1
while number <= 5:
print(number, 'squared is', number**2)
number = number + 1
if number == 4:
break
1 squared is 1
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 59/119
4/19/2021 The Ultimate Python Beginner's Handbook
2 squared is 4
3 squared is 9 Forum Donate
number = 0
while number < 5:
number = number + 1
if number == 4:
continue
print(number, 'squared is', number**2)
1 squared is 1
2 squared is 4
3 squared is 9
5 squared is 25
The most important difference is that you can easily iterate over
sequential types.
Basic Syntax
The basic syntax of a for loop is as below.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 61/119
4/19/2021 The Ultimate Python Beginner's Handbook
BMW
Forum Donate
Ferrari
McLaren Learn to code — free 3,000-hour curriculum
The list of cars contains three items. The for loop will iterate over
the list and store each item in the car variable, and then execute a
statement, in this case print(car) , to print each car in the console.
range() function
The range function is widely used in for loops because it gives you a
simple way to list numbers.
This code will loop through the numbers 0 to 5 and print each of them.
0
1
2
3
4
numbers = [0, 1, 2, 3, 4]
for number in numbers:
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 62/119
4/19/2021 The Ultimate Python Beginner's Handbook
print(number)
Forum Donate
0
1
2
3
4
Here we are starting in 5 and a stoping in 10. The number you set to
stop is not included.
5
6
7
8
9
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 63/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
for number in range(10, 20, 2):
Learn to code — free 3,000-hour curriculum
print(number)
10
12
14
16
18
else block
When the items in the list are over, the else block will be called.
BMW
Ferrari
McLaren
No cars left!
Simply use the break keyword, and the loop will stop itsForum
execution. Donate
BMW
Ferrari
The loop will iterate through the list and print each car.
In this case, after the loop reaches 'Ferrari', the break is called and
'McLaren' won't be printed.
BMW
McLaren
In this case, I have three lists: one of BMW models, another on Ferrari
models, and nally one with McLaren models.
The rst loop iterates over each brand's list, and the second will
iterate over the models of each brand.
car_models = [
['BMW I8', 'BMW X3',
'BMW X1'],
['Ferrari 812', 'Ferrari F8',
'Ferrari GTC4'],
['McLaren 570S', 'McLaren 570GT',
'McLaren 720S']
]
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 66/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
BMW I8 Learn to code — free 3,000-hour curriculum
BMW X3
BMW X1
Ferrari 812
Ferrari F8
Ferrari GTC4
McLaren 570S
McLaren 570GT
McLaren 720S
I will brie y demonstrate how to make a basic loop over each one of
them.
Bob
Mary
Forum Donate
Learn
people = {'Bob', to code — free 3,000-hour curriculum
'Mary'}
Bob
Mary
Bob
Mary
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 68/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
30
25
Functions
As the code grows the complexity also grows. And functions help
organize the code.
Functions are a handy way to create blocks of code that you can reuse.
In the line after the declaration starts, remember to indent the block
of code.
def print_first_function():
print('My first function!')
print_first_function()
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 69/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
My first function!
return a value
Use the return keyword to return a value from the function.
def second_function():
return 'My second function!'
print(second_function())
My second function!
Forum Donate
return_numbers() returns two values simultaneously.
Learn to code — free 3,000-hour curriculum
def return_numbers():
return 10, 2
print(return_numbers())
(10, 2)
Arguments
You can de ne parameters between the parentheses.
One Argument
To specify one parameter, just de ne it inside the parentheses.
used.
Forum Donate
def my_number(num):
return 'My number is: ' + str(num)
print(my_number(10))
My number is: 10
Here we have a function that adds two numbers called add . It expects
two arguments de ned by first_num and second_num .
The arguments are added by the + operator and the result is then
returned by the return .
print(add(10,2))
12
This example is very similar to the last one The only difference is that
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 72/119
4/19/2021 The Ultimate Python Beginner's Handbook
This example is very similar to the last one. The only difference is that
we have 3 parameters instead of 2. Forum Donate
print(add(10,2,3))
15
Default value.
You can set a default value for a parameter if no argument is given
using the = operator and a value of choice.
print(my_number(10))
print(my_number())
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 73/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
My number is:Learn
10 to code — free 3,000-hour curriculum
My number is: 30
This example ips the arguments, but the function works as expected
because I tell it which value goes to which parameter by name.
print(my_numbers(second_number=30, first_number=10))
arguments as necessary.
Forum Donate
def my_numbers(*args):
for arg in args:
print(number)
my_numbers(10,2,3)
10
2
3
def my_numbers(**kwargs):
for key, value in kwargs.items():
print(key)
print(value)
my_numbers(first_number=30, second_number=10)
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 75/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
first_number
30
second_number
10
def my_sport(sport):
print('I like ' + sport)
my_sport('football')
my_sport('swimming')
I like football
I like swimming
def my_numbers(numbers):
for number in numbers:
print(number)
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 76/119
4/19/2021 The Ultimate Python Beginner's Handbook
my_numbers([30, 10, 64, 92, 105])
Forum Donate
30
10
64
92
105
Scope
The place where a variable is created de nes its availability to be
accessed and manipulated by the rest of the code. This is known as
scope.
Global Scope
A global scope allows you to use the variable anywhere in your
program.
name = 'Bob'
def print_name():
print('My name is ' + name)
print_name()
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 77/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
Notice that the function could use the variable name and print My nam
e is Bob .
Local Scope
When you declare a variable inside a function, it only exists inside that
function and can't be accessed from the outside.
def print_name():
name = "Bob"
print('My name is ' + name)
print_name()
My name is Bob
The variable name was declared inside the function, so the output is
the same as before.
def print_name():
name = 'Bob'
print('My name is ' + name)
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 78/119
4/19/2021 The Ultimate Python Beginner's Handbook
p ( y )
Forum Donate
print(name)
Learn to code — free 3,000-hour curriculum
I tried to print the variable name from outside the function, but the
scope of the variable was local and could not be found in a global
scope.
Mixing Scopes
If you use the same name for variables inside and outside a function,
the function will use the one inside its scope.
On the other hand, when calling print() outside the function scope,
name="Sarah" is used because of its global scope.
name = "Sarah"
def print_name():
name = 'Bob'
print('My name is ' + name)
print_name()
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 79/119
4/19/2021 The Ultimate Python Beginner's Handbook
My name is Bob
Sarah
List Comprehensions
Sometimes we want to perform some very simple operations over the
items of a list.
Basic syntax
To use a list comprehension to replace a regular for loop, we can make:
numbers = [1, 2, 3, 4, 5]
new_list = []
for n in numbers:
new_list.append(n**3)
print(new_list)
Forum Donate
numbers = [1, 2, 3, 4, 5]
new_list = []
print(new_list)
Regular way
numbers = [1, 2, 3, 4, 5]
new_list = []
for n in numbers:
if(n > 3):
new_list.append(n**3)
print(new_list)
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 82/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
[64, 125]
numbers = [1, 2, 3, 4, 5]
new_list = []
print(new_list)
[64, 125]
numbers = [1, 2, 3, 4, 5]
new_list = []
def cube(number):
return number**3
print(new list)
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 83/119
4/19/2021 The Ultimate Python Beginner's Handbook
print(new_list)
Forum Donate
[64, 125]
Lambda Functions
A Python lambda function can only have one expression and can't
have multiple lines.
Basic Syntax
The basic syntax is very simple: just use the lambda keyword, de ne
the parameters needed, and use ":" to separate the parameters from
the expression.
16
The declaration of the function and the execution will happen in the
same line.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 85/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
(lambda multiplier, number, exponent : multiplier * number**exponent)(2,
Learn to code — free 3,000-hour curriculum
16
Filter
The Filter function will lter the list based on the expression.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 86/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
numbers = [2, Learn
5, 10]to code — free 3,000-hour curriculum
filtered_list = list(filter(lambda number : number > 5, numbers))
print(filtered_list)
[10]
Modules
After some time your code starts to get more complex with lots of
functions and variables.
You can write a module with all the mathematical operations and
other people can use it.
And, if you need, you can use someone else's modules to simplify your
code, speeding up your project.
Using a Module
To use a module we use the import keyword.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 87/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
As the name implies we have to tell our program what module to
Learn to code — free 3,000-hour curriculum
import.
import math
math.e
2.718281828459045
import math as m
m.sqrt(121)
m.sqrt(729)
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 88/119
4/19/2021 The Ultimate Python Beginner's Handbook
11
27 Forum Donate
This example uses the floor() function that returns the largest
integer less than or equal to a given number.
floor(9.8923)
Creating a Module
Now that we know how to use modules, let's see how to create one.
Learn to code
def multiply(first_num, — free 3,000-hour curriculum
second_num):
return first_num * second_num
import basic_operations
basic_operations.add(10,2)
basic_operations.subtract(10,2)
basic_operations.multiply(10,2)
basic_operations.divide(10,2)
12
8
20
5.0
if __name__ == '__main__'
You are in the process of building a module with the basic math
operations add , subtract , multiply , and divide called basic_oper
ations saved in the basic_operations.py le.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 90/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
Learnsecond_num):
def add(first_num, to code — free 3,000-hour curriculum
return first_num + second_num
print(add(10, 2))
print(subtract(10,2))
print(multiply(10,2))
print(divide(10,2))
12
8
20
5.0
Forum Donate
Let's import the new module run it in the Python console.
Learn to code — free 3,000-hour curriculum
20
5.0
>>>
When the module is imported our tests are displayed on the screen
even though we didn't do anything besides importing basic_operatio
ns .
if __name__ == '__main__':
print(add(10, 2))
print(subtract(10,2))
print(multiply(10 2))
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 92/119
4/19/2021 The Ultimate Python Beginner's Handbook
print(multiply(10,2))
print(divide(10,2)) Forum Donate
Running the code directly on the terminal will continue to display the
tests. But when you import it like a module, the tests won't show and
you can use the functions the way you intended.
Now that you know how to use the if __name__ == '__main__' , let's
understand how it works.
This variable represents the name of the module which is the name of
the .py le.
print(__name__)
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 93/119
4/19/2021 The Ultimate Python Beginner's Handbook
__main__
This tells us that when a program is executed directly, the variable __n
ame__ is de ned as __main__ .
Files
Creating, deleting, reading, and many other functions applied to les
are an integral part of many programs.
L t' h t h dl l i P th
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 94/119
4/19/2021 The Ultimate Python Beginner's Handbook
Let's see how to handle les in Python.
Forum Donate
The rst argument is the name of the le we are handling, the second
refers to the operation we are using.
You can also use the w mode to create a le. Unlike the x mode, it will
not throw an exception since this mode indicates the writing mode. We
are opening a le to write data into it and, if the le doesn't exist, it is
created.
The last one is the a mode which stands for append. As the name
implies, you can append more data to the le, while the w mode
simply overwrites any existing data.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 95/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
When appending, if the le doesn't exist, it also creates it.
Learn to code — free 3,000-hour curriculum
File
To write write
data into a le, you simply open a le with the w mode.
Then, to add data, you use the object return by the open() function.
In this case, the object is called people_file . Then you call the write()
function passing the data as argument.
We use \n at the end to break the line, otherwise the content in the
le will stay in the same line as "BobMarySarah".
One more detail is to close() the le. This is not only a good practice,
but also ensures that your changes were applied to the le.
Remember that when using w mode, the data that already existed in
the le will be overwritten by the new data. To add new data without
losing what was already there, we have to use the append mode.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 96/119
4/19/2021 The Ultimate Python Beginner's Handbook
Learn tonew
The a mode appends codedata
— free
to 3,000-hour curriculum
the le, keeping the existing one.
In this example, after the rst writing with w mode, we are using the
a mode to append. The result is that each name will appear twice in
the le "people.txt".
#first write
people_file = open("people.txt", "w")
people_file.write("Bob\n")
people_file.write("Mary\n")
people_file.write("Sarah\n")
people_file.close()
File read
Reading the le is also very straightforward: just use the r mode like
so.
If you read the "people.txt" le created in the last example, you should
see 6 names in your output.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 97/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
The read() function reads the whole le at once. If you use the read
line() function, you can read the le line by line.
Bob
Mary
Sarah
You can also loop to read the lines like the example below.
Bob
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 98/119
4/19/2021 The Ultimate Python Beginner's Handbook
ob
Mary Forum Donate
Sarah
Bob Learn to code — free 3,000-hour curriculum
Mary
Sarah
Delete a File
To delete a le, you also need the os module.
import os
os.remove('my_file.txt')
import os
if os.path.exists('my_file.txt'):
os.remove('my_file.txt')
else:
print('There is no such file!')
Copy a File
For this one, I like to use the copyfile() method from the shutil
d l
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 99/119
4/19/2021 The Ultimate Python Beginner's Handbook
module.
Forum Donate
copyfile('my_file.txt','another_file.txt')
There are a few options to copy a le, but copyfile() is the fastest
one.
move('my_file.txt','another_file.txt')
That's why when you check the type of a variable you can see the cla
ss keyword right next to its type (class).
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 100/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
This code snippet shows that my_city is an object and it is an instance
of the class strLearn
. to code — free 3,000-hour curriculum
<class 'str'>
Your new mission is to build the new product for the company, a new
model called 747-Space. This aircraft ies higher altitudes than other
commercial models.
Boeing needs to build dozens of those to sell to airlines all over the
world, and the aircrafts have to be all the same.
This way you make the project once, and reuse it many times.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 101/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
In our code example before, consider that every string has the same
Learn to code — free 3,000-hour curriculum
behavior and the same attributes. So it only makes sense for strings to
have a class str to de ne them.
methods.
For example, a string has many built-in methods that we can use.
They work like functions, you just need to separate them from the
objects using a . .
In this code snippet, I'm calling the replace() method from the string
variable my_city which is an object, and an instance of the class str .
The replace() method replaces a part of the string for another and
returns a new string with the change. The original string remains the
same.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 102/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
Old York
New York Learn to code — free 3,000-hour curriculum
Creating a Class
We have used many objects (instances of classes) like strings, integers,
lists, and dictionaries. All of them are instances of prede ned classes
in Python.
To create our own classes we use the class keyword.
By convention, the name of the class matches the name of the .py le
and the module by consequence. It is also a good practice to organize
the code.
class Vehicle:
def __init__(self, year, model, plate_number, current_speed = 0):
self.year = year
self.model = model
self.plate_number = plate_number
self.current_speed = current_speed
def move(self):
self.current_speed += 1
def stop(self):
self.current_speed = 0
def vehicle_details(self):
return self.model + ', ' + str(self.year) + ', ' + self.plate_num
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 103/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
The class keyword is used to specify the name of the class Vehicle .
And one method to give back information about the vehicle: def vehi
cle_details(self) .
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 104/119
4/19/2021 The Ultimate Python Beginner's Handbook
_ ( )
Forum Donate
The implementation inside
Learn to codethe methods
— free workcurriculum
3,000-hour the same way as in
functions. You can also have a return to give you back some value at
the end of the method as demonstrated by def vehicle_details(sel
f) .
Now use the methods to move() the car which increases its current_
speed by 1, accelerate(10) which increases its current_speed by
the value given in the argument, and stop() which sets the current_
speed to 0.
f hi l i t V hi l
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 105/119
4/19/2021 The Ultimate Python Beginner's Handbook
>>> from vehicle import Vehicle
>>> Forum Donate
>>> my_car = Vehicle(2009, 'F8', 'ABC1234', 100)
>>> Learn to code — free 3,000-hour curriculum
print(my_car.current_speed)
100
>>> my_car.move()
>>> print(my_car.current_speed)
101
>>> my_car.accelerate(10)
>>> print(my_car.current_speed)
111
>>> my_car.stop()
>>> print(my_car.current_speed)
0
>>> print(my_car.vehicle_details())
F8, 2009, ABC1234
Inheritance
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 106/119
4/19/2021
Inheritance The Ultimate Python Beginner's Handbook
Donate Forum
Let's de ne a generic Vehicle class and save it inside the vehicle.py
Learn to code — free 3,000-hour curriculum
le.
class Vehicle:
def __init__(self, year, model, plate_number, current_speed):
self.year = year
self.model = model
self.plate_number = plate_number
self.current_speed = current_speed
def move(self):
self.current_speed += 1
def stop(self):
self.current_speed = 0
def vehicle_details(self):
return self.model + ', ' + str(self.year) + ', ' + self.plate_num
The de nition of vehicle in the Vehicle is very generic and might not
be suitable for trucks, for instance, because it should include a cargo
attribute.
On the other hand, a cargo attribute does not make much sense for
small vehicles like motorcycles.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 107/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum
When a class (child) inherits another class (parent), all the attributes Donate
and methods from the
Learn toparent
code — class are inherited
free 3,000-hour by the child class.
curriculum
The Truck class is called a child class that inherits from its parent class
Vehicle .
A parent class is also called a superclass while a child class is also known
as a subclass.
Create the class Truck and save it inside the truck.py le.
class Truck(Vehicle):
def __init__(self, year, model, plate_number, current_speed, current_
super().__init__(year, model, plate_number, current_speed)
self.current_cargo = current_cargo
The class Vehicle inside the parentheses when de ning the class Tr
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 108/119
4/19/2021 The Ultimate Python Beginner's Handbook
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 109/119
4/19/2021 The Ultimate Python Beginner's Handbook
Exceptions
Errors are a part of every programmer's life, and knowing how to deal
with them is a skill on its own.
If some piece of code runs into an error, the Python interpreter will
raise an exception.
Types of Exceptions
Let's try to raise some exceptions on purpose and see the errors they
produce.
TypeError
'I am a string' + 32
IndexError
NameError
print(my_variable)
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 112/119
4/19/2021 The Ultimate Python Beginner's Handbook
ZeroDivisionError
error, as expected.
32/0
This was just a sample of the kinds of exceptions you might see during
your daily routine and what can cause each of them.
Exception Handling
Now we know how to cause errors that will crash our code and show
us some message saying something is wrong.
try:
32/0
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 113/119
4/19/2021 The Ultimate Python Beginner's Handbook
3 /0
except: Forum Donate
print('Dividing by zero!')
Learn to code — free 3,000-hour curriculum
Dividing by zero!
Put the block of code that may cause an exception inside the try
scope. If everything runs alright, the except block is not invoked. But
if an exception is raised, the block of code inside the except is
executed.
This way the program doesn't crash and if you have some code after
the exception, it will keep running if you want it to.
try:
car_brands = ['ford', 'ferrari', 'bmw']
print(car_brands[3])
except IndexError:
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 114/119
4/19/2021 The Ultimate Python Beginner's Handbook
except IndexError:
print('There is no such index!') Forum Donate
You can use a tuple to specify as many exception types as you want in
a single except :
try:
print('My code!')
except(IndexError, ZeroDivisionError, TypeError):
print('My Excepetion!')
else
It is possible to add an else command at the end of the try/except .
It runs only if there are no exceptions.
My variable
No NameError
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 115/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
Raising Exceptions
The raise command allows you to manually raise an exception.
try:
raise IndexError('This index is not allowed')
except:
print('Doing something with the exception!')
raise
finally
The finally block is executed independently of exceptions being
raised or not.
They are usually there to allow the program to clean up resources like
les, memory, network connections, etc.
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 116/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
try:
Learn to code — free 3,000-hour curriculum
print(my_variable)
except NameError:
print('Except block')
finally:
print('Finally block')
Except block
Finally block
Conclusion
That's it!
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 117/119
4/19/2021 The Ultimate Python Beginner's Handbook
Forum Donate
If you read this Learn
far, tweet to —
to code the author
free to show
3,000-hour them you care.
curriculum
Tweet a thanks
Our mission: to help people learn to code for free. We accomplish this by creating thousands of
videos, articles, and interactive coding lessons - all freely available to the public. We also have
thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers,
services, and staff.
Trending Guides
Our Nonpro t
About Alumni Network Open Source Shop Support Sponsors Academic Honesty
https://www.freecodecamp.org/news/the-python-guide-for-beginners/ 119/119