Masterpythonfundamentalstheultimateguideforbeginners Sample
Masterpythonfundamentalstheultimateguideforbeginners Sample
PYTHON
FUNDAMENTALS
The Ultimate Guide for Beginners
Benjamin Bennett Alexander
"Python" and the Python Logo are trademarks of the Python Software Foundation.
1 | Page
2 | Page
Copyright © 2022 by Benjamin Bennett Alexander
All rights are reserved. No part of this publication may be
reproduced, stored in a retrieval system, or transmitted in any form
or by any means, electronic, mechanical, photocopying, recording,
or otherwise, without prior permission of the publisher.
Every effort has been made in the preparation of this book to ensure
the accuracy of the information presented. However, we do not
warrant or represent its completeness or accuracy.
3 | Page
Feedback and Reviews
I welcome and appreciate your feedback and reviews. Please consider
writing a review on the platform you purchased this book from. We rely
on your reviews to reach more people. Please send your queries to:
[email protected]. Thank you.
4 | Page
Table of Contents
Feedback and Reviews 4
Introduction 9
Your First Code 12
1.Python Syntax and Variables 13
Comments in Python 13
Indentation in Python 14
Quotation Marks 14
Python Variables 14
Multiple Variables and Values 16
Reassigning Variables 16
Variable Names in Python 17
Allowed Variable Names in Python 17
Illegal Variable Names 18
Python Reserved Keywords 19
Best Practices for Creating Variable Names 20
Chapter One Summary 22
End of Chapter Challenges 22
2.Data Types in Python 24
Numeric Data Types 24
Boolean Data Types 26
Data Sequences in Python 27
Strings 27
Accessing String Characters 28
Formatted String Literals 29
Format Strings Function 29
String Escape Methods 30
The len() Function 31
String Methods 32
Lists 35
List Properties 35
Math Operations on Lists 38
List Functions 38
Lists Methods 39
Tuples 47
Tuples Methods 47
Other Data types in Python 49
Sets 49
Creating Sets 49
Set Properties 50
5 | Page
Sets Methods 52
Frozen Sets 56
Python Dictionary 56
Creating a Dictionary 56
Dictionary Keys 57
Accessing Dictionary Keys and Values 57
Dictionaries are Ordered 60
Merging Dictionaries 60
Dictionary Methods 61
Nested Dictionaries 63
Typecasting in Python 64
Chapter Summary 66
End of Chapter Questions 66
3.Operators in Python 68
Arithmetic Operators 68
Comparison Operators in Python 71
Membership Operators in Python 73
Logical Operators in Python 74
Identity Operators in Python 75
Chapter summary 76
End of Chapter Challenges 76
4.Python Math 78
Built-in Math Functions 78
The Math Module 79
Chapter Summary 82
End of Chapter Challenges 82
5.User input 84
Creating a Simple Calculator 84
Chapter Summary 86
End of Chapter Challenge 86
6.Python Functions 88
Creating Functions 88
Adding Default Arguments to Functions 90
Python *args and **kwargs 94
Local and Global Scope in Functions 95
Functions are First-Class Citizens 96
Pure Functions 97
Chapter Summary 99
End of Chapter Challenges 99
7.Lambda Functions 101
Using Lambda Functions 102
End of Chapter Challenge 104
6 | Page
8.Conditional Statements 106
Elif Statement 106
Else Statement 107
Conditional Statements Flowchart 108
Nested if-Statements 109
Logical Operators in if-Statements 109
Shorthand Syntax 110
Chapter Summary 112
End of Chapter Challenges 112
9. For Loops 114
Iterating Through a String 114
Iterating over a Dictionary 115
Iterating Through a Range 116
The Break Statement 117
The Continue Statement 117
Nested For Loops 118
List Comprehension and For Loops 119
Else Statement in For Loops 120
Chapter Summary 121
End of Chapter Challenges 121
10. While Loops 123
The Break Statement 123
The Continue Statement 124
The Else Statement 124
Password Checker 125
Chapter Summary 125
End of Chapter Challenges 125
11. Error handling in Python 127
Try and Except Blocks 127
The Else Statement 129
The Finally Statement 129
Chapter Summary 132
End of Chapter Challenge 132
12. Classes in Python 134
Creating a Class 134
__init__ Method and Self Parameter 135
Class Methods 137
Deleting Class Objects 138
Inheritance 139
Polymorphism 140
Encapsulation 141
Public vs Private Members 141
7 | Page
Chapter Summary 144
End of Chapter Challenge 144
13. File handling 146
Creating Files 146
Writing Files 146
Reading Files 147
Appending Files 147
Closing Files 148
Using with Statement 148
Deleting Files 149
Chapter Summary 150
End of Chapter Challenges 150
14. Modules and Pip 152
Creating a Module 152
Importing Module 153
Python Pip 153
Using Modules: Random Module 154
Using Modules: Flask Module 155
Using Modules: Pandas Module 156
The Zen of Python 157
The Help Function 157
Chapter Summary 159
End of Chapter Challenges 159
15. Time and Date 161
The Time Module 161
The timeit() Function 164
The DateTime Module 164
Chapter Summary 167
End of Chapter Challenge. 167
Answers to Challenges 168
Acknowledgements 184
About Author 185
8 | Page
Introduction
The purpose of this book is to help you master the fundamentals of the
Python language. If you are reading this book, you have an interest in
mastering the fundamentals of Python. That is a great thing. The book
tackles the basic and intermediate concepts of Python. This makes it ideal
for people that are starting on their Python journey, or those trying to
brush up on their Python skills.
Why should you learn Python? You should learn Python because it gives
you superpowers. Python is a general-purpose programming language. It
is used in machine learning, web development, big data, data engineering,
game development, and so much more. Learning Python opens up plenty
of opportunities for you. Python is a high-level programming language.
This means it is not necessary to have a deep understanding of how things
work under the hood to use Python. It is user-friendly with an easy-to-
read syntax. It can be integrated with other programming languages. The
popularity of Python has continued to rise since its release in 1991 by
Guido van Rossum. Python is currently the number-one programming
language in the world. Python is open source and has a huge community.
As a Python programmer, you will never feel alone.
What are you going to learn from this book? You will learn about Python
syntax and variables. We will dive deep into the data types in Python. We
will look at operators in Python. This book also covers Python math,
functions, loops, classes, modules, and so forth. For every concept
introduced, there is an example code to demonstrate it. Difficult concepts
are explained in simpler terms, to ensure your understanding. At the end
of each chapter, you will tackle some challenges that will test your
understanding.
So, how should you read this book? For you to get the best out of this book,
engage in active learning. Do not just read code, but write it down and run
it. Don’t copy, and paste the code in the book, type it down. At the end of
each chapter, try solving the challenges without looking at the solution.
The fundamentals that you will learn in this book will come in handy once
you start building big applications. So, learn them well. Mastering
9 | Page
fundamentals will make it easy for you to learn other programming
languages in the future.
10 | Page
Downloading Python and IDE
The first thing that you need to do to work with Python, is to install it on
your machine. This book uses Python 3. If you do not have Python
installed on your machine, visit the link below to install it on your
computer: https://www.python.org/downloads/
Download the version that is compatible with your machine. Ensure that
you download the latest version of Python.
Now, to write and execute code you will need a code editor or an
Integrated Development Environment (IDE) to be installed on your
machine. Python IDLE shell comes pre-installed with Python. To use the
shell, just type Python in the search bar and press enter. The Python
window will open.
Below are other IDEs and text editors that you can use. I recommend
Pycharm, but feel free to use the one you are comfortable with:
❖ Pycharm
Download the community version from the link below:
https://www.jetbrains.com/pycharm/download/#section=windows
❖ Jupyter notebook
Use the link below to find out how you can install the Jupyter notebook
on your machine.
https://jupyter.org/install.html
❖ Sublime
You can download sublime text from the link below:
https://www.sublimetext.com/download
❖ Atom
https://atom.en.uptodown.com/windows
You can explore any of these and settle for the one that you are
comfortable with.
11 | Page
Your First Code
Now that you have installed Python and an IDE, it is time to write your
first code. You will type print(‘hello, world’) as per the tradition of
the programming word. Now run your code. The output should be:
Hello, world.
Congratulations, You have officially created your first Python program.
12 | Page
1.Python Syntax and Variables
Let us start by defining what syntax is in Python. It is a set of rules of how
code should be written to be understood by a Python interpreter. Think of
syntax as the grammar rules of the Python language. Just like a normal
language has rules that we must adhere to, to be understood by the next
person, our code should be understood by the interpreter. Throughout
this book, we are going to be learning about the proper way of writing
Python code. We will learn about indentation, quotation marks,
docstrings, and so forth. A code that is not written in proper Python
syntax will always raise an error and will stop our program from running.
Comments in Python
When you start a line with the (#) hash sign, you are telling the interpreter
that you are writing a comment. Comments are not executable. The
Python interpreter will ignore all comments. Comments are used to
explain what the code is doing. Below is an example of a comment using
the hash (#) sign.
# This is a comment in Python
# This is another comment in Python
If the comment is a multiline comment, then every line should start with
the hash (#) sign. A docstring begins with triple quotes (" " ") and is closed
by another (" " ") triple quotes. Docstring is an abbreviation for
documentation string. It explains the functionality of a function, class, or
module. Unlike a normal comment with a (#) sign, a docstring can be read
by the interpreter using the __doc__method.
def myfunc():
print(myfunc.__doc__)
Output
This explains the function
13 | Page
Indentation in Python
In Python, indentation is used to indicate that something is part of a block
of code. A block of code starts with a colon (:) at the end of a statement.
The code that comes after the colon, is expected to be indented. In Python,
indentation is 4 spaces (hit the spacebar 4 times). We shall learn more
about this later. Below you can see that the print() statement is indented
because it's part of a function.
def func():
print('Hello world')
Quotation Marks
Quotation marks surrounding an object indicate that it is a string. We
shall learn more about strings later on in this book. Python uses double
(“) and single (‘) quotation marks to indicate strings. Here are two
examples of two lines of code using single and double quotation marks.
print('Hello world')
print("hello world")
print("""hello world""")
Python Variables
A variable is a reserved memory location for an object. Think of a variable
as a ‘container’ where an object is stored. An object is assigned to a
variable. Python uses the = sign to assign an object to a variable. The
variable is always on the left side of the equal (=) sign and the object is
always on the right side of the sign. Look at the example below:
Example 1
x = 2
print(x + 2)
Output:
4
Example 2
greeting = 'hello world'
print(greeting)
Output:
hello world
14 | Page
In the above code (example 1), 2 is the object stored in the variable x. To
access 2, we have to call the variable x, which is the point of reference for
object 2. To reiterate, a variable is not an object; it is a point of
reference for an object. X is the variable and 2 is the object. When we
run print(x + 2) we get an output of 4 because 2 is stored in x, so we are
simply adding 2 to 2. In Example 2, when we print(greeting) our output
is ‘hello world’ because the greeting(variable) is simply a container that
has been assigned an object called ‘hello world’.
Since greeting is simply a container, we can change the object assigned to
it, and it will print out a different object. See below:
greeting = 'goodbye world'
print(greeting)
Output:
goodbye world
As you will see throughout this book, we can assign variables to different
data types – floats, strings, integers, Boolean values, complex numbers,
lists, tuples, dictionaries, sets, etc. See some examples below:
#assigning a variable to a dictionary
names = {'first': 'John','last':'Brown'}
15 | Page
Multiple Variables and Values
In Python, we can assign multiple variables to a single value. Here is an
example below:
x = y = 23
print(x + y)
Output:
46
In the above code, both x and y hold the same value; that’s why our output
is 46.
We can also assign different variables to multiple values. The number of
variables should be equal to the number of values. In the example below,
we have three (3) variables assigned to three (3) values.
a, b, c = 12, 'Love', False
print(a)
print(b)
print(c)
Output:
12
Love
False
Reassigning Variables
Once a variable is created, it can be reassigned to a different value. The
new value will overwrite the old value. In the code below the ‘old me’ value
has been replaced with the ‘new me’ value in the variable x.
x = 'old me'
x = 'new me'
print(x)
Output:
new me
16 | Page
Variable Names in Python
In Python, we can create different types of variable names. However,
some variable names are legal and some are not allowed. We will look at
variable names that are allowed and not-allowed in Python. We will also
explore best practices when it comes to picking variable names for our
code.
num = 2
Num = 3
NUM = 4
print(num + Num + NUM)
Output:
9
_name = 'John'
print(_name)
Output:
John
We can use underscore ( _ )to separate two words in a variable name. See
below:
first_name = 'John'
print(first_name)
Output:
John
17 | Page
We can use numbers in a variable name as long as the number is not the
first character of the variable name.
name9 = 'John'
print(name9)
Output:
John
Example 2
first-name = 'John'
print(first-name)
Output:
first-name = 'John'
^
SyntaxError: cannot assign to operator
Variable names cannot start with a number. The example below generates
a syntax error because we are trying to start a variable name with a
number.
9name = 'John'
print(9name)
Output:
9name = 'John'
^
SyntaxError: invalid syntax
18 | Page
We cannot use space to separate words in a variable name. It will generate
a syntax error. See below:
first name = 'John'
print(first name)
Output:
first name = 'John'
^
SyntaxError: invalid syntax
Python Reserved Keywords
Reserved words are words with a special meaning in Python. We cannot
use Python reserved keywords as variable names. If we use any of these
keywords, our code will generate an error. To find a list of keywords,
import the module keyword (modules are covered later). Use the kwlist()
method to extract a list of reserved keywords in Python. All the words
listed in the output below will generate an error if used as variable names.
import keyword
print(keyword.kwlist)
Output:
['False', 'None', 'True', '__peg_parser__', 'and', 'as',
'assert', 'async', 'await', 'break', 'class', 'continue',
'def', 'del', 'elif', 'else', 'except', 'finally', 'for',
'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
'nonlocal', 'not', 'or', 'pass', 'raise', 'return',
'try', 'while', 'with', 'yield']
When we try to use one of the words in the list of keywords as a variable
name, the code generates a syntax error because we are not allowed to use
the word False as a variable name. See below:
False = bool
print(False)
Output:
False = bool
^
SyntaxError: cannot assign to False
19 | Page
x = "John asked Mary, \n\"How long are you in
town?\"."
print(x)
Output:
John asked Mary,
"How long are you in town?".
You can see from the above output that part of our string has been written
in a new line. What happens when we use (\t)? See below:
x = "John asked Mary, \t\" How long are you in town?\"."
print(x)
Output:
John asked Mary, " How long are you in town?".
(\t) is a tab escape method, that is why we now have a tab space in our
code output. Here is a table of some escape characters in Python.
31 | Page