You are on page 1of 346

MASTER

PYTHON
FUNDAMENTALS
The Ultimate Guide for Beginners
Benjamin Bennett Alexander

"Python" and the Python Logo are trademarks of the Python Software Foundation.

1 | 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.

2 | 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:
benjaminbennettalexander@gmail.com. Thank you.

3 | Page
contents
Feedback and Reviews ...................................................... 3
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 Summary ...........................................................................................22
Challenges .......................................................................................................22

2.Data Types in Python ............................................... 24


Numeric Data Types ...................................................................................... 24
Boolean Data Types ....................................................................................... 26
The None Type ............................................................................................... 26
Data Sequences in Python .............................................................................. 27
Strings ............................................................................................................. 27
Accessing String Characters ........................................................................... 27
Formatted String Literals .............................................................................. 28
Format Strings Function ............................................................................... 29
String Escape Methods .................................................................................. 29
The len() Function .......................................................................................... 31
String Methods ............................................................................................... 31
Lists .................................................................................................................34
List Properties ................................................................................................. 35
Math operations on lists ................................................................................. 37
List Functions ................................................................................................ 38
Lists Methods ..................................................................................................39
Tuples ..............................................................................................................45
Tuples Methods ............................................................................................. 46
Other Data Types in Python ........................................................................... 47
Sets .................................................................................................................. 47
Creating Sets ................................................................................................... 47

4 | Page
Set Properties ................................................................................................. 48
Sets Methods .................................................................................................. 50
Frozen Sets ...................................................................................................... 53
Dictionary ........................................................................................................54
Creating a Dictionary ......................................................................................54
Dictionary Keys ............................................................................................... 55
Accessing Dictionary Keys and Values .......................................................... 55
Dictionaries are Ordered ................................................................................ 57
Merging Dictionaries ..................................................................................... 58
Dictionary Methods ....................................................................................... 58
Nested Dictionaries ........................................................................................ 61
Typecasting in Python .................................................................................... 61
Chapter Summary ...........................................................................................63
Challenges .......................................................................................................63

3.Operators in Python ................................................ 65


Arithmetic Operators......................................................................................65
Comparison Operators in Python ................................................................. 68
Membership Operators in Python .................................................................70
Logical Operators in Python .......................................................................... 71
Identity Operators in Python ......................................................................... 72
The Unpacking *Operator .............................................................................. 72
Unpacking a Dictionary using **Operator .................................................... 73
Chapter summary ........................................................................................... 74
Challenges ....................................................................................................... 74

4.Python Math............................................................ 76
Built-in Math Functions ................................................................................. 76
The Math Module ........................................................................................... 77
Chapter Summary .......................................................................................... 80
Challenges ...................................................................................................... 80

5.User Input ............................................................... 82


Creating a Simple Calculator ........................................................................ 82
Chapter Summary .......................................................................................... 83
Challenge ........................................................................................................ 83

6.Python Functions .................................................... 85


Creating Functions ........................................................................................ 85
The Pass Statement ....................................................................................... 86
Adding Parameters and Arguments to Functions ....................................... 86
Adding Default Arguments to Functions ......................................................87
The Return Statement in Functions ..............................................................87
Returning Multiple Values ............................................................................ 88

5 | Page
The Yield Statement ...................................................................................... 89
Python *args and **kwargs ............................................................................ 91
Type Hints ...................................................................................................... 92
Local and Global Scope in Functions ............................................................93
Functions are First-Class Citizens ................................................................ 94
Creating Decorators ........................................................................................ 97
Adding Variables to the Decorator ............................................................... 99
Using a Decorator as a Timer ...................................................................... 100
Pure Functions .............................................................................................. 101
Chapter Summary ......................................................................................... 102
Challenges ..................................................................................................... 102

7.Lambda Functions ................................................. 104


Using Lambda Functions ............................................................................. 105
Chapter Summary ......................................................................................... 106
Challenge ....................................................................................................... 106

8.Conditional Statements ......................................... 108


Elif Statement ...............................................................................................108
Else Statement .............................................................................................. 109
Conditional Statements Flowchart .............................................................. 110
Nested If-Statements ..................................................................................... 111
Logical Operators in If Statements ............................................................... 111
Shorthand Syntax ......................................................................................... 112
Chapter Summary ......................................................................................... 113
Challenges ..................................................................................................... 113

9. For Loops .............................................................. 115


Iterating over a String .................................................................................. 115
Iterating over a Dictionary ........................................................................... 116
Iterating through a Range .............................................................................117
The Break Statement .................................................................................... 118
The Continue Statement............................................................................... 118
Nested For Loops .......................................................................................... 119
List Comprehension and For Loops ............................................................ 120
The Else Statement in For Loops ................................................................. 121
Chapter Summary ......................................................................................... 122
Challenges ..................................................................................................... 122

10. While Loops ......................................................... 124


The Break Statement .................................................................................... 124
The Continue Statement............................................................................... 125
The Else Statement ....................................................................................... 125
Password Checker ......................................................................................... 126

6 | Page
Chapter Summary ......................................................................................... 126
Challenges ..................................................................................................... 126

11. Error handling in Python......................................128


Try and Except Blocks .................................................................................. 128
The Else Statement ....................................................................................... 130
The Finally Statement .................................................................................. 130
Chapter Summary ......................................................................................... 133
Challenge ....................................................................................................... 133

12. Classes in Python ................................................. 135


Creating a Class............................................................................................. 135
Class Attributes ............................................................................................. 135
Instance Attributes ....................................................................................... 136
Class Instances .............................................................................................. 137
Class Methods and Instance Methods ......................................................... 138
Static Methods .............................................................................................. 140
Self in Classes ................................................................................................ 141
Deleting Class Objects .................................................................................. 143
Inheritance .................................................................................................... 144
Polymorphism ............................................................................................... 145
Encapsulation ............................................................................................... 146
Public vs Private Members ........................................................................... 146
Chapter Summary ......................................................................................... 149
Challenge ....................................................................................................... 149

13. File handling ........................................................ 151


Creating Files ................................................................................................ 151
Writing Files.................................................................................................. 151
Reading Files ................................................................................................. 152
Appending Files ............................................................................................ 152
Closing Files .................................................................................................. 153
Using the With Statement ............................................................................ 153
Deleting Files ................................................................................................ 154
Chapter Summary ......................................................................................... 155
Challenges ..................................................................................................... 155

14. Modules and Pip .................................................. 157


Creating a Module ........................................................................................ 157
Importing Modules ....................................................................................... 158
Python Pip ..................................................................................................... 158
Using Modules: random ............................................................................... 159
Using Modules: flask .................................................................................... 160
Using Modules: pandas ................................................................................ 161

7 | Page
The Zen of Python ......................................................................................... 163
The Help Function ........................................................................................ 163
Chapter Summary ......................................................................................... 164
Challenges ..................................................................................................... 164

15. Time and Date ......................................................166


The Time Module .......................................................................................... 166
The timeit Module ........................................................................................ 169
The datetime Module ................................................................................... 169
Chapter Summary ..........................................................................................171
Challenge ........................................................................................................171

Answers to Challenges............................................... 172


Part 2-Practice Questions .......................................... 185
Syntax and Variables .................................................................................... 186
Data Types and Typecasting ........................................................................ 191
Python Tuples ............................................................................................... 195
Lists in Python .............................................................................................. 198
Python Sets................................................................................................... 203
Operators in Python .................................................................................... 204
Strings and Boolean Values......................................................................... 208
Python Dictionary ......................................................................................... 211
Functions in Python ..................................................................................... 215
Conditional Statements ............................................................................... 220
For Loops ..................................................................................................... 223
While Loops ................................................................................................. 228
Python Math ................................................................................................ 230
User Input .................................................................................................... 234
Python’s Variable Scope ...............................................................................235
Error Handling ............................................................................................ 236
Pip and Modules .......................................................................................... 238
Dates in Python ............................................................................................ 240
Lambda Functions ....................................................................................... 242
Python Classes ............................................................................................. 244
File Handling ............................................................................................... 249
Extra Challenges ........................................................................................... 251
Answers to Practice Questions .................................................................... 254

Other Books by Author ............................................. 342

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 the 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 to solve the challenges without looking at
the solution. At the end of the book, you will find over 300 questions
to test your knowledge of the fundamentals.

9 | Page
The fundamentals that you will learn in this book will come in handy for
whatever path you decide to take with Python. Whether you want to go
into web development, machine learning, data analysis, data science,
data engineering, etc., you will need to master these fundamentals.

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, use 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. The 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 world. 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 for
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 in order 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 program 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 quote. "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():

""" This explains the function"""


pass

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 four spaces (hit the spacebar four
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 three
examples of three 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 run 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'}

#assigning a variable name to a list


names = ['John', 'Lloyd', bool]

#assigning a variable name to a tuple


names = ( 'John', 'Lloyd')

#assigning a variable name to a set


names = {'John', 'Peter'}
#assigning a variable name to a floating number
num = 2.0
#assign a variable name to a string
name = "Lloyd"

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. 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
programs.

Allowed Variable Names in Python


Python's syntax is restrictive when it comes to variable names. It allows
us to create only certain types of variable names. If you do not follow
these rules, your code will always raise an error. Let’s look at the allowed
variable names in Python.
We can start variable names with either lowercase or uppercase letters.
We can have a variable name with only lowercase letters or a variable
name with only uppercase letters. It is all legal in Python. Note that
variable names in Python are case-sensitive, so num is not equal to Num
or NUM. Here are some examples of variations of variable names:
num = 2
Num = 3
NUM = 4
print(num + Num + NUM)
Output:
9

We can start variable names with an underscore sign (_).

_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

Illegal Variable Names


We cannot start a variable name with a dash (-). We cannot use a dash
(-) to separate words in a variable name. Our code will generate an error
if we do any of these. See below:
Example 1
-name = 'John'
print(-name)
Output:
-name = 'John'
^
SyntaxError: cannot assign to operator

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's 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). In Python, use
the kwlis () method to get a list of reserved keywords. All the words listed
below will generate an error if used as variable names.
import keyword

print(keyword.kwlist)
Output:
['False', 'None', 'True', '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
Do not use built-in functions as variable names, even though they are
not reserved keywords. For example, we should not use the word list as
a variable name because it is a built-in function in Python. Our code will
not generate an error if we use it as a variable name. But, when we try
to use the list() function in the same file to create a list, it will not work.
Once we use a built-in function name as a variable name, all references
to the built-in function don't work. It is good practice to steer clear of
using all built-in functions as variable names. In the example below, we
create a list with a variable name list. When we try to create a list using
the list() function, we get a type error because the list() function gets
overshadowed by the list variable.
#creating a list named list
list = [7, 4]
print(list)
# Creating a list using the list built-in function
list2 = list((3,4))
Output:
[7, 4]
list2 = list((3,4))
TypeError: 'list' object is not callable

Best Practices for Creating Variable Names

When it comes to variable names, you are at liberty to create any type of
name as long as it is allowed. However, just because it is allowed, it does
not mean it is best practice. There are best practices that we must adhere
to when creating variable names. Choosing the right variable name will
improve the readability of our code. Here are some of the best practices
when it comes to creating variable names.
Variable names must be lowercase and separated by underscores if there
is more than one word. Below, we create a variable called first_names.
We separate the two words with an underscore (_). See the example
below:
first_names = ['Mary','Peter','Ben','kim']

Use descriptive variable names that describe what the object is about to
improve the readability of the code. If you are creating an object about
age, you may want to use the word age as a variable name. If you create
an object about names, include the word "name" in the variable name.

20 | Page
Below, we create a list of names of students in a school. To make our
variable descriptive, we use the name "student_names." When you read
the variable name, you will know what kind of information the variable
is holding.
student_names = ['Mary','Peter','Ben','kim']

When naming a class (we will talk about classes later), start each word
with a capital letter. If you are using two words in your variable name,
start each word with a capital letter—without space between them. This
style is CamelCase. See the example below of a class variable called "last
names." We combined the words and used capital letters as the first
letter for each word.
class LastNames:
pass

For production, avoid using abbreviations as they are not descriptive


enough. If using one-letter names, avoid using small letters of the letters
O and L because they are mistaken for numbers 0 and 1. It is also
important to ensure that we keep the variable names as concise as
possible. Avoid variable names that are too long.

21 | Page
Chapter Summary
❖ Python syntax is a set of rules for how code should be written to be
understood by a Python interpreter.
❖ Comments in Python start with a hash sign (#) or are surrounded by
triple quotes (""") called a docstring.
❖ Indentation is used to indicate that something is part of a block of
code.
❖ A variable is a reserved memory location for an object.
❖ A variable is assigned to an object using the equal sign (=).
❖ Multiple variables can be assigned to the same value.
❖ Python reserved words should not be used as variable names.
❖ You must adhere to the best practices when creating variable names.

Challenges
1. What is the difference between a comment and a docstring in
Python?

2. Assign variables x and y to the value of 23.

3. Is Python case-sensitive?

22 | Page
Chapter 2:
Data Types in Python

23 | Page
2.Data Types in Python
Data types are classifications of data in Python. As we will see, different
operations are performed on the data depending on its classification.
The primary data types in Python are numeric, Boolean, sequence
(strings, lists, and tuples), hashtable (sets, and dictionaries), and
nonetype. In this chapter, we will explore these data types in Python.

Numeric Data Types


Integer or int is any number that has no decimal point. It can be
positive or negative. There is no limit to how long the list can be. In
Python, you can check the data type of an object using the built-in
function type(). Below, we have created variables called x and assigned
them different values. When we check the variable types using the type()
function, they are all classified as integers.
x = 0
print(type(x))
x = 5
print(type(x))
x = 25
print(type(x))
x = 250
print(type(x))
x = -25
print(type(x))
x = -10000000000909000909090099900
print(type(x))
Output:
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>

Float or floating number is any number that has a decimal point. It


can be negative or positive. There is no limit to how long the number can
be. Here are examples of floating numbers. Let’s check the data type of
the variable below using the type() function.

24 | Page
x = 0.1
print(type(x))
x = 5.909
print(type(x))
x = 25.56
print(type(x))
x = 250.66666666777
print(type(x))
x = -25.7
print(type(x))
x = -10000000000909000909090099900.66
print(type(x))
Output:
<class 'float'>
<class 'float'>
<class 'float'>
<class 'float'>
<class 'float'>
<class 'float'>

Complex numbers is another data type that you will encounter is a


complex number. A complex number is represented by (a + jb). It has a
real and an imaginary component. The letter "a" represents the real
part, and the letter "b" is the imaginary component. The imaginary part
is denoted by j. If you replace "a" and "b" with numbers and leave "j"
the way it is, then you have created a complex function. See variable x in
the example below. We can also create a complex number using the
complex (real, imaginary) function. The real part is accessed by the
real() attribute. The imag() attribute accesses the imaginary part. Here
is an example of a complex data type and how we can access the real and
imaginary parts:
x = 5 + 2j
print(type(x))
print(x.real)
print(x.imag)
Output:
<class 'complex'>
5.0
2.0

25 | Page
Let’s create another complex number using the complex () function.
Code below:
complex1 = complex(5,2)
print(type(complex1))
print(f'The real part is:{complex1.real}')
print(f'The imaginary part is:{complex1.imag}')
Output:
<class 'complex'>
The real part is: 5.0
The imaginary part is: 2.0

Boolean Data Types


Boolean or bool – This is an in-built data type in Python that
represents two values—True or False. In Python, a Boolean data type
will return the truth about an expression. Anything that evaluates to
True or False is a Boolean class. In the below example, the expression
evaluates if 5 is greater than 2. The expression evaluates to True because
5 is greater than 2. If we check the type of x, it will return a bool class.
x = 5 > 2
print(x)
Output
True

Checking the class type of x.


x = 5 > 2
print(type(x))
Output:
<class 'bool'>

The None Type


The None data type represents null values in Python. So, None is not
zero, it simply means no value, a NoneType. For example, if you have a
function that does not return anything, it returns a NoneType. Here is
how we confirm the None data type.
x = None
print(type(x))
Output:
<class 'NoneType'>

26 | Page
Data Sequences in Python
Let’s look at the sequence data types that you will find in Python. The
three sequence data types that we will look at are strings, lists, and
tuples.

Strings

In Python, a string is an array or sequence of characters. Each character


of the string can be accessed separately by referring to its index
(position). Strings are enclosed in single, double, or triple quotation
marks. Take note of the difference in the number of quotation marks in
the strings below. All three variables below are valid strings in Python.
a = 'Am learning Python'

b = "Am learning"

c = '''Am learning
Python'''

print(type(a))
print(type(b))
print(type(c))
Output:
<class 'str'>
<class 'str'>
<class 'str'>

Accessing String Characters

x = 'I love Python'


# Accessing the first character of the string
print(x[0])

"I love Python" is a string literal because its object is surrounded by


quotation marks. Using indexing (x [0]), we can access the first
character of the string. The output below is 'I' because it is the letter
sitting at index zero (note that in Python, counting starts at zero). The
first character of the string is sitting at position zero (0). Space between
words is also indexed.
Output:
I

27 | Page
Using indexing, we can also grab a bunch of characters at the same time.
Let's say we want to access the word "love" from our string. We can
access it using indexing. The first letter we are accessing is sitting at
index 2, so we enter 2 between the square brackets first. The last letter
is sitting at index 5, so we enter 6 after the colon (:) to access index 5.
x = 'I love Python'
# Accessing the first character of the string
print(x[2:6])
Output:
love

We can also iterate through a string using a for loop (we will look at for
loops later in the book). But here is a simple code to demonstrate that.
Using a loop and indexing, we have flipped the string (front to back).
x = 'I love Python'
for i in x:
print(x[7:14], i, x[2:6],)
break
Output:
Python I love

Formatted String Literals


Formatted string literals, or f-strings, are one of the string formatting
mechanisms available in Python. F-strings make it easy to embed
expressions inside quotation marks (string literals). F-strings start with
the letter f followed by quotation marks (f""). The expression is written
between the quotation marks. Here is an example of an f-string:
name = "Ben"
eyes = "brown"

str1 = f"Hi my name is {name}. My eyes color is {eyes}."


print(str1)
Output:
Hi my name is Ben. My eyes color is brown.

Notice that to include the variables in the f string, we put the variable
names inside the curly brackets {}.

28 | Page
Format Strings Function

Another way we can format strings is using the string format function.
year = 2019
age = 55

str1 = 'I have been studying Python since {}'\


'.I am {} years old.'
print(str1.format(year, age))

In the above code, we have combined integers (year, age) and a string
(str1), using the format() function. The curly brackets in the string
indicate where we want the numbers to be placed in the string. Take note
of the order of the arguments in the format() function; the year comes
first and the age comes second because that is the order we want the
arguments to appear in our string. We can also use index values to
indicate where we want the numbers to be placed. Here is the code
below:
Str1 = 'I have been studying Python since {0}'\
'. I am {1} years old.'
print(str1.format(year, age))

Notice that we have placed numbers between the curly brackets of our
string. The {0} indicates that we want to place the first item in the
format() function there. Year is at index zero(0) in our code, so it comes
first, and age is at index (1), so it comes second.The format() function
can take an unlimited number of arguments. Here is the output of the
code below:
Output:
I have been studying Python since 2019. I am 55 years old.

String Escape Methods


Let us write a simple Python code to demonstrate the importance of
escape methods.
x = "John asked Mary, "How long are you in town"."
print(x)
Output:
x = "John asked Mary, "How long are you in town"."
^^^
SyntaxError: invalid syntax

29 | Page
The above code generates a syntax error because we are trying to put
double quotation marks inside a string with double quotation marks. So,
how do we write a proper string that will have double quotation marks
inside a string and will not generate an error? We use an escape
character. An escape character allows us to insert characters into a string
that are otherwise not allowed. That escape character is the backslash
(\). In our case, the backslash allows us to escape the string of double
quotation marks and insert another set of double quotation marks. Here
is how we use them in our code to avoid the syntax error:
x = "John asked Mary, \"How long are you in town?\"."
print(x)
Output:
John asked Mary, "How long are you in town?".
You can see from the output that we have now avoided the syntax error.
Note that if we have a string of single quotation marks, we can put
double quotation marks inside the string and it will not generate an
error.
We can also use escape characters if we want to write part of our string
on a new line. To do that, we start with the backslash ( \ ) and then we
insert the character that tells the interpreter to write part of the string
on a new line. That character is (n). When we combine the two, we get (
\n ). Here is how it looks in the code:

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 on 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?".

30 | Page
In the code above, we are using a tab escape method (\t). That is why we
now have a tab space in our code output. Here is a table of some escape
characters in Python.

Escape Character Operation


1 \n Starts a new
2 \t Creates tab space
3 \\ Inserts a backslash in the string
4 \b Gets rid of backspace in a string
5 \’ Single quote
6 \r Carriage return

The len() Function

The len() function is used to return the length of the string. Here is an
example of how we can use it in code.
str1 = 'Am learning Python'
print(len(str1))
Output:
18

The whitespaces in strings are indexed. That is why the len() function
returns 18 as the length of the string above.

String Methods
String methods are functions that can be performed on strings. Let's
look at some of those methods.
The capitalize() method
Capitalize, as the name suggests, capitalizes the first letter of a string.
The first letter of our string below is small. If we want to capitalize that
part, we use the capitalize() method. You can see below that only the
first letter has been capitalized.
Str1 = 'am learning Python'
print(str1.capitalize())
Output
Am learning python

31 | Page
The upper() method
Unlike the capitalize() method, which only capitalizes the first letter, the
upper() method will capitalize the whole string. Let’s try it on the string
we used for the capitalize() method. The output shows that the whole
string has been capitalized.
str1 = 'am learning Python'
print(str1.upper())
Output:
AM LEARNING PYTHON

The lower() method


The lower() method is the opposite of the upper() method. It converts
the whole string into lowercase.
str1 = 'AM LEARNING PYTHON'
print(str1.lower())
Output:
am learning python

The islower() method


This method checks if the string is lowercase. If the string is lowercase,
it will return a Boolean value of True; otherwise, it will return False. In
the code below, our code output is False. What do you think is the reason
for that?
str1 = 'My house is beautiful'
print(str1.islower())
Output:
False

The isupper() method


This method checks if the string is in uppercase. If the string is
uppercase, it will return a Boolean value of True. If it is not, it will return
False.
Str1 = 'My house is beautiful'
print(str1.isupper())
Output
False

32 | Page
The replace() method
Let’s say you have a string and you want to replace part of that string
with another word; the replace() method will help you do that. In the
code below, we want to replace the word "learning" with "studying."
Check out how the replace() method makes that look so easy.
str1 = 'Am learning to be a doctor'
str1 = str1.replace('learning','studying')
print(str1)
Output:
Am studying to be a doctor

The split() method


The split() method will split a string at a specified separator. A separator
could be a comma, space, etc. You have to specify where the split should
be. Let’s try to split the code below. We are going to split the string
between the word spaces. The output is a list of strings.
str1 = 'Am learning to be a doctor'
str1 = str1.split(" ")
print(str1)
Output:
['Am', 'learning', 'to', 'be', 'a', 'doctor']

The strip() method


The strip() method removes spaces and specified characters before and
after a string. In the code below, we are going to use the strip() method
to remove the #$ charactrs at the beginning and end of our string. We
pass the characters we want to remove between the parenthesis as
arguments. See an example below.
str1 = ' #Am learning to be a doctor$ '
str1 = str1.strip(" #$ ")
print(str1)
Output:
Am learning to be a doctor

33 | Page
The count() method
If you want to know how many times a certain object appears in a string,
you can use the count() method. Let’s use the method to check how
many times the word "learning" appears in our string. We will use the
word "learning" as the argument of the method. Our output is 1 because
that is how many times the word appears in our string.
str1 = 'Am learning to be a doctor'
str1 = str1.count('learning')
print(str1)
Output:
1

The index() method


The index() method searches for a specified element and returns its
index. It works similar to the index() method in lists. You pass the value
that you want to search for as the argument. You can also specify where
you want the search to start and end. In the code below, we are searching
for the index of the word "learning," and we specify where the search
should start (index 2) and end (index 17). The output is 3 because that
is where the word "learning" is found.
str1 = 'Am learning to be a doctor'
str1 = str.index('learning',2,17)
print(str1)
Output:
3

Lists
In Python, a list is a sequence data type that stores data in square
brackets. The elements in a list are separated by commas. Here is an
example of a list.
age = [23, 34, 45, 56, 67, 78]

We can confirm the class type of the list by using the type() function.
age = [23, 34, 45, 56, 67, 78]
print(type(age))
Output:
<class 'list'>

34 | Page
A list can contain different types of data. We can have a list of strings,
integers, floats, Boolean values, and so forth. Below are different types
of lists that we can create in Python. The examples below are not
exhaustive.
# A list of integers
numbers_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# A list of floats
float_list = [1.2, 3.5, 2.45, 1.1]
# A list of strings
fruits = ['orange', 'mango', 'apple']
# A list of boolean values
bool_values = [True, False]
# A list of boolean values, strings, and integers
mixed_list = [1, True, 'orange', 9]
# A list of lists (nested list)
nested_list = [['mango', 'orange'], [1, 2, 4]]

List Properties
1 A list is ordered
2 A list is mutable
3 A list can have duplicates
4 A list can have different types of data

Let’s explore each of the properties in some detail.

Lists are ordered


Lists are ordered or indexed. Every element in the list has a position. To
access that item, we use its position or index. The first item in a list is
sitting at position 0, or index 0. In the list of numbers below, let’s say we
want to print out number 78; we will access number 78 by referencing
its position. Its index or position is 5, so we put 5 between the square
brackets. Here is how we do it below:

age = [23, 34, 45, 56, 67, 78]


print(age[5])
Output:
78

35 | Page
We can also access more than one item from the list. Let’s say we want
to print numbers 45 to 78. Here is how we do it using list slicing. List
slicing returns another list.
age = [23, 34, 45, 56, 67, 78]
print(age[2:6])
Output:
[45, 56, 67, 78]

Try it yourself. Try accessing numbers 34–56 using indexing. With


slicing, you get better at it by practicing. You can also do negative slicing,
that is, counting from right to left. This is how the code would look if we
wanted to access numbers 34–67 using negative indexing.
age = [23, 34, 45, 56, 67, 78]
print(age[-5:-1])

Lists are mutable


Lists are changeable. You can add and delete elements from a list at
anytime. Nothing about a list is permanent. Here are some examples.
Let’s say we want to change the first element of our list; we can do it
using indexing.
age = [23, 34, 45, 56, 67, 78]
age[0] = 25
print(age)

[0] is the index of the item we want to change, and [25] is the new
number we want to replace [23] with.
Output:
[25, 34, 45, 56, 67, 78]

We can also delete elements from the list using the del statement by
calling the index of the element we want to delete. Let’s delete numbers
23, 34, and 35 from our list using slicing:
age = [23, 34, 45, 56, 67, 78]
del age[:2]
print(age)
Output:
[45, 56, 67, 78]

36 | Page
Lists can have duplicates

Lists can store duplicates. Our list of names below has two people named
Rose. When we print it out, both names get printed out.
names = ["Rose","Rose", "Kennedy", "Moses"]
print(names)
Output:
['Rose', 'Rose', 'Kennedy', 'Moses']

Lists can hold arbitrary objects

A list can store arbitrary elements. You can have Boolean values,
integers, strings, floats, and other lists (nested lists) all in one list.
mixed_list = ["Rose","Rose",23, False, "Kennedy", 23.7,
"Moses", [3, 4, 4, 4]]
print(mixed_list)
Output:
['Rose', 'Rose', 23, False, 'Kennedy', 23.7, 'Moses', [3, 4,
4, 4]]

Math Operations on Lists


We can also carry out math operations on lists, like multiplication and
addition.
Below, we double the list of elements using multiplication.
age = [23, 34, 45, 56, 67, 78] * 2
print(age)
Output:
[23, 34, 45, 56, 67, 78, 23, 34, 45, 56, 67, 78]

Here we concatenate two lists using the + operator.


age = [23, 34, 45, 56, 67, 78] + [12,34,67,89]
print(age)
Output:
[23, 34, 45, 56, 67, 78, 12, 34, 67, 89]

37 | Page
List Functions
Function Description
len() Returns the length of the list
min() Returns the min value of the list
max() Returns the max value of the list

The len() Function


If we want to know how long our list is, we can use the len() function.
The list variable is passed as the argument. We get an output of 5
because we have 5 names on our list.
names = ["John", "Rose", "Kennedy", "Moses", "Terry"]
print(len(names))
Output:
5

The min() Function


If we want to know the minimum value in our list, we can use the min()
function. What do you think would be the outcome of this code? And,
why do we get that outcome? Think about it.
names = ["Rose","John" "Kennedy", "Moses",
"Terry", "Ronald"]
print(min(names))

The max() Function


The max() function returns the maximum element of the list. In our
example below, the output is 78 because that’s the biggest number on
our list.
age = [23, 34, 45, 56, 67, 78]
print(max(age))
Output:
78

38 | Page
Lists Methods
We saw earlier that lists are mutable; this makes it possible to perform
functions on the list using list methods. What are the list methods? List
methods are functions that you can use on a list. To call a method, we
call the list (object), we put a dot (.) in front of the object, and after the
dot comes the method—object.method(). We are going to look at the list
methods in Python that you need to know in detail. I will also introduce
you to list comprehensions in Python.

List Methods
1 append() 7 pop()
2 extend() 8 count()
3 copy() 9 index()
4 remove() 10 insert()
5 sort() 11 reverse()
6 clear() 12 join()

The append() method


The append() method only adds one item at a time to the end of a list. If
you want to add more than one item, you can use the extend method
(which we are going to look at later). The append method only takes one
argument. Here is an example of the append method in action. We are
using append to add the name Rose to the end of the list.
names = ['John','Oscar','Faith']
names.append('Rose')
print(names)
Output:
['John', 'Oscar', 'Faith', 'Rose']

The extend() method


If you want to add an iterable to the list, you can use the extend()
method. Unlike the append() method, which only adds one item at the
end of the list, the extend() method can add any number of items that
are in an iterable. The extend method always adds items at the end of
the list. Every item passed as an argument in the extend method will be
treated as an iterable. If you pass a string as an argument, it will iterate

39 | Page
over the string. In the example below, we use the extend method to add
two names from an iterable (another list).
names = ['John', 'Oscar', 'Faith', 'Eric', 'Oscar']
names_2 = ['Rose', 'Terry']
names.extend(names_2)
print(names)
Output:
['John', 'Oscar', 'Faith', 'Eric', 'Oscar', 'Rose', 'Terry]

The copy() method


The copy() method creates a copy of a list. In the example below, we
use the copy method to create a copy of our original list. The copy()
method takes no arguments.
names = ['John', 'Oscar', 'Faith', 'Eric', 'Oscar']
names2 = names.copy()
print(names2)
Output:
['John', 'Oscar', 'Faith', 'Eric', 'Oscar']

The remove() method


The remove() method deletes the argument passed to it. The remove
method does not take the index of the item we want to delete; it takes
the actual name of the item. If the element does not exist, it will raise an
error. If the list contains more than one element with the same name,
the remove method will only remove the element with the lowest index.
Here is an example below:
names = ['John', 'Oscar', 'Faith',
'Eric', 'Oscar']
# Use the remove method to remove a name from the list
names.remove('Oscar')
print(names)
Output:
['John', 'Faith', 'Eric', 'Oscar']

40 | Page
The sort() method
The sort() method sorts a list in ascending order (by default). It can also
be used to sort a list in descending order by setting the reverse argument
to True (see the below example). It can be used to sort numbers and
words. However, a list should contain only numbers or only strings for
the sort method to work. In the examples below, we sort the list of names
in ascending order and the list of numbers in descending order.
Example 1 Ascending
names = ['John', 'Oscar', 'Faith', 'Eric']
# sorting the list
names.sort()
print(names)
Output:
['Eric', 'Faith', 'John', 'Oscar']

Example 2 Descending
results = [12, 34, 5, 6, 18, 34, 18, 27]
results.sort(reverse=True)
print(results)
Output:
[34, 34, 27, 18, 18, 12, 6, 5]

The clear() method


The clear() method removes all the items from the list. It leaves you with
an empty list. It takes no arguments. Here is an example below:
names = ['John', 'Oscar', 'Faith', 'Eric', 'Oscar']
names.clear()
print(names)
Output:
[ ]

41 | Page
The pop() method
By default, the pop() method removes the last element or value in a
given list. Let’s say we have a list of names—['John', 'Oscar', 'Faith'], and
we want to remove the name 'Faith' from the list. We can use the pop()
method to remove the name. Here is an example below:
# Using the pop method to remove the last item
names = ['john', 'Oscar', 'Faith']
print(names.pop())
Output:
Faith

However, with the pop() method, we can also specify which element we
want to remove from a given list. We pass the element’s index as the
argument. Let’s say we want to remove the name Oscar from our list; we
will use index 1 as the argument of the pop method. See below (next
page):
# Removing Oscar using pop and indexing
names = ['John', 'Oscar', 'Faith']
names.pop(1)
print(names)
Output:
['John', 'Faith']

LIFO and Lists


The pop() method makes it possible to use a list as a stack; that is, the
last item added to the list is the first item to be removed; that is, Last in,
First Out (LIFO). Let’s use an example to illustrate this. You can see
from the example below that Eric was the last name added to the list of
names, but when we use the pop method, Eric is removed first.
names = ['John', 'Oscar', 'Faith']
# adding another name to the list
names.append('Eric')
print(names)

#Using pop to remove the item


names.pop()
print(names)
Output:
['John', 'Oscar', 'Faith', 'Eric']
['John', 'Oscar', 'Faith']

42 | Page
FIFO and Lists
We can also use a list as a queue. The first item to be added will be the
first item to be removed; that is, First in, First Out (FIFO). To do that,
we need to import deque from the collections module (modules are
covered in chapter 14). In the example below, we append two names to
our list, but when we use the popleft() method from the collections
module, it is the name at index zero that is popped (John).
from collections import deque

names = deque(['John','Oscar', 'Faith'])


names.append('Eric')
names.append('David')
names.popleft()
print(names)
Output:
deque(['Oscar', 'Faith', 'Eric', 'David'])

The count() method


The count() method counts how many times a given item appears in the
list. In the example below, we are checking how many times the name
Eric appears in the list. You can see that the name Eric only appears once
in the list because our output is 1.
names = ['John', 'Oscar', 'Faith', 'Eric']
print(names.count('Eric'))
Output:
1

The index() method


The index() method returns the position or index of the given element.
This is possible because a list is ordered. We are going to use the index()
method to search for the position of the name ‘Oscar’ in our list. If the
name Oscar appears more than once, the index() method is only going
to return the lowest index. In our example below, the name Oscar
appears twice in the list, but the index() method only returns the lowest
index, index 1.
names = ['John', 'Oscar', 'Faith', 'Eric', 'Oscar']
print(names.index('Oscar'))
Output:
1

43 | Page
In the index() method, we can also pass the position we want our search
for the given item to begin at and the position we want it to end at (this
is optional). In the example below, we tell the index() method where to
start (index 2) searching and where to end (index 5) the search for
Oscar. Since we are telling it to skip index one (1), it will only return the
next lowest index of the name Oscar in the list, which is index 4.
names = ['John', 'Oscar', 'Faith', 'Eric', 'Oscar']
print(names.index('Oscar',2,5))
Output:
4

The insert() method


The insert() method adds a specified item to the list. The insert()
method takes two arguments: the position or index of the item and the
name of the item that you want to add to the list. In the example below,
we are telling the insert() method to add the name "Peter" at index 0 to
the list of names.
names = ['John', 'Oscar', 'Faith', 'Eric', 'Oscar']
names.insert(0,'Peter')
print(names)
Output:
['Peter', 'John', 'Oscar', 'Faith', 'Eric', 'Oscar']

The reverse() method


The reverse() method simply does what it says, reversing the order of
the list. It takes no argument. It does not sort the list; it only reverses it.
The first becomes the last, and the last becomes the first. Check the
example below:
names = ['John', 'Oscar', 'Faith', 'Eric', 'Oscar']
names.reverse()
print(names)
Output:
['Oscar', 'Eric', 'Faith', 'Oscar', 'John']

The join() method


At its most basic, the join() method takes an iterable (whose values are
strings) and returns a string of elements joined by the string separator.

44 | Page
If an iterable has non-string elements, the string method returns an
error. Here is the syntax below:

String.join(iterable)
The string in the above syntax is the separator. We can use anything to
be a separator or joiner.
a = ['1', '2', '3', '4', '5', '6']
# Using joing method
a = "".join(a)
print(a)
Output:
123456

In the code above, we have an iterable, list "a." Notice that all the
elements in the iterable (list a) are strings. The join() method separator
is the two quotation marks ("") with nothing in-between. So, we are
telling the join() method to return a string joined by nothing. That’s why
the output is a sequence separated by nothing. If we put something
between the quotation marks (separator), we will get a string joined by
that separator. See the example below:
a = ['1', '2', '3', '4', '5', '6']
# Adding a separator #
a = "#".join(a)
print(a)
Output:
1#2#3#4#5#6

Tuples
A tuple is a Python sequence structure that is immutable. Tuples are
permanent. You cannot add, remove, or delete elements from a tuple.
Tuples can be created by either using round brackets () or using the in-
built function tuple(). Here are examples of how we can create tuples.
Method 1
animals = ('Lion', 'Tiger', 'Elephant')
print(type(animals))
Output:
<class 'tuple'>

45 | Page
Method 2
Another way to create a tuple is by using the built-in tuple() function.
Take note of the double brackets.
animals = tuple(('Lion', 'Tiger', 'Elephant'))
print(type(animals))
Output:
<class 'tuple'>

Tuples Methods
While it is impossible to modify a tuple, there are some methods that we
can perform on them. Let’s look at the two tuple methods.

The count() method


The count() method counts how many times a particular item appears
in a tuple. It takes one argument. If you don’t pass any arguments or you
pass more than one argument, it will return an error. Let’s say we want
to check how many times the lion element appears in our tuple; here is
how we do it using the count() method.
animals = tuple(('Lion', 'Tiger', 'Elephant'))
lion = animals.count('Lion')
print(lion)
Output:
1

The index() method


Since tuples are ordered, it is possible to find the position of the
elements in the tuple using indexing. Let's use indexing to find the
position of "Tiger" in our tuple of animals below.
animals = tuple(('Lion', 'Tiger', 'Elephant'))
tiger = animals.index('Tiger')
print(tiger)
Output:
1

You can see from the output that Tiger appears at position or index one
(1). With the indexing method, you can also specify the index where the
search for the element should start and where it should end. In the code
below, we want the search to start at index 3 and end at index 5.

46 | Page
animals = tuple(('Tiger', 'Elephant','Hippo',
'Giraffe','Lion'))
tiger = animals.index('Lion',3,5)
print(f'The lion is sitting at index {tiger}')
Output:
The lion is sitting at index 4

Other Data Types in Python


Let’s look at the other data types in Python. We are going to look at sets
and dictionaries.

Sets
Sets are another data type that we find in Python. Unlike lists that are
ordered, sets have no order or sequence. A set is mutable. You can add
and remove elements from a set. However, you cannot change an
element once it has been added to the set. Simply put, you can modify a
set, but you cannot replace its elements.

Creating Sets
There are two ways that you can create a set. The first one is using curly
brackets. Here is an example:
animals = {'Lion','Tiger','Elephant', 'Cheetah'}
print(type(animals))
Output:
<class 'set'>

However, you cannot declare an empty set using brackets. Empty curly
brackets will be interpreted as a dictionary, not a set. Let’s run the code
below to see what happens:
animals ={}
print(type(animals))
Output:
<class 'dict'>

Another way to create sets is by using the in-built set() function. Take
note of the double brackets.
animals = set(('Lion','Tiger','Elephant', 'Cheetah'))
print(type(animals))
Output:
<class 'set'>

47 | Page
Set Properties
Sets can be created using {}brackets or set constructor
Sets don’t allow duplicates
Sets are not ordered
Sets are mutable
Sets can hold arbitrary elements

Duplicates are not permitted in sets


We can have duplicates in a list, as we saw earlier in the list section, but
you cannot have duplicates in a set. This makes sets a great alternative
to lists if you are trying to get rid of duplicates in your data. Below is an
example of what happens once we try to create a set with a duplicate.
animals = {'Lion','Tiger','Elephant',
'Cheetah', 'Lion'}
print(animals)
You can see from the output below that even though we have added two
lions to our set, our set is only acknowledging one lion. The second "lion"
is ignored.
Output:
{'Cheetah', 'Elephant', 'Tiger', 'Lion'}

If an element is already in the set and we try to add it again, the set will
simply ignore it. Let’s try to add an elephant to our set of animals.
animals = {'Lion','Tiger','Elephant',
'Cheetah', 'Lion'}
animals.add('Elephant')
print(animals)
Output:
{'Cheetah', 'Elephant', 'Tiger', 'Lion'}

Sets are not ordered


Elements in a set have no particular order. That is why you cannot use
an index to access them. When we create a set, notice how the order of
the set changes when we print it out. We are going to create a set of
random numbers and print them out. Notice how the output is in a
different order to our original set? Every time you print out the set, the
order may change. That is because set elements have no particular
index.

48 | Page
num_set ={12, 78, 19, 0, 78, 67, 55}
print(num_set)
Output:
{0, 67, 19, 55, 12, 78}

Sets can be changed


Sets are mutable. We can add elements to a set and remove elements
from a set. However, we cannot change an element of the set once it has
been added to the set. We are going to use an example to demonstrate
this. Let’s create a set of cars, then we shall try to add a car to the set,
and then we will try to remove a car from the set. Adding an element to
the set is a success; we can see that from the output below.
cars ={"Honda", "Suzuki", "Benz"}
cars.add('Tesla')
print(cars)
Output:
{'Suzuki', 'Honda', 'Tesla', 'Benz'}

Removing an object from a set is a success. The Benz car is no longer in


the set.
cars ={"Honda", "Suzuki", "Benz"}
cars.remove('Benz')
print(cars)
Output:
{'Honda', 'Suzuki', 'Tesla'}

Replacing an object from a set is not possible because set objects are not
mutable. Remember that the set itself is mutable, but not its objects.
This is the reason you cannot add a list to a set, because a list is mutable.
When we try to add a list to a set (see example below), the code raises an
error because the list fails the immutability test. It is for the same reason
that we cannot have nested sets: sets themselves are mutable. See below
what happens when we try to add a list to a set:
cars ={"Honda", "Suzuki", "Benz"}
cars.add(['Tesla','BMW'])
print(cars)
Output:
cars.add(['Tesla','BMW'])
TypeError: unhashable type: 'list'

49 | Page
Sets can have arbitrary objects.
Sets can have floats, integers, strings, and so forth. We can have a set of
different objects. The example below demonstrates just that.
mixed_set ={"Honda", "Suzuki", "Benz", 2,
False, (2, 3, 8)}
print(mixed_set)
Output:
{False, 2, (2, 3, 8), 'Honda', 'Benz', 'Suzuki'}

Sets Methods
Set methods are functions that we can perform on a set. They work just
like list methods—object.method(). We have already seen some sets of
methods in action above (add and remove methods). Let’s look at some
of the methods in detail.

The pop() method


The pop() method removes a random element from a set. In a list, the
pop method by default removes the last element in the list. But since sets
are not ordered, the pop() method removes any element from the set.
When you use the pop() method, you will not know which element gets
removed.
cars ={"Honda", "Suzuki", "Benz", "Tesla"}
cars.pop()
print(cars)
Output:
{'Benz', 'Tesla', 'Honda'}

Every time you run the above code, you will get a different output
because a different item gets popped. The set pop() method takes no
arguments.

50 | Page
The remove() method
As we have seen earlier, the remove() method removes a specified
element from a set. The remove() method will return an error if you pass
an element that is not in a set . Let’s see the remove() method in action
using an example.
cars ={"Honda", "Suzuki", "Benz", "Tesla"}
cars.remove("Honda")
print(cars)
Output:
{'Tesla','Benz', 'Suzuki'}

Now, let’s try removing an element that does not exist in the set.
cars ={"Honda", "Suzuki", "Benz", "Tesla"}
cars.remove("BMW")
print(cars)

You can see from the output that our code generates an error because
we tried to remove 'BMW', which is not in the set.
Output:
cars.remove("BMW")
KeyError: 'BMW'

The discard() method


The discard() method works like the remove() method. The only
difference is that the discard() method will not raise an error if an
element does not exist. We are going to use the same example we used
for the remove method to show this.
cars = {"Honda", "Suzuki", "Benz", "Tesla"}
cars.discard("BMW")
print(cars)
The output below is not an error but just the original set.
Output:
{'Honda', 'Suzuki', 'Tesla', 'Benz'}

51 | Page
The copy() method
The copy() method returns a copy of the set.
cars ={"Honda", "Suzuki", "Benz", "Tesla"}
cars2 = cars.copy()
print(cars2)
Output:
{'Tesla', 'Honda', 'Suzuki', 'Benz'}

The add() method


The add() method adds an element to the set. It takes only one
argument. What do you think will happen if you try to add more than
one argument? Try it out.
names = {'Jane','Josh', 'Kate'}
names.add('Mary')
print(names)
Output:
{'Mary', 'Josh', 'Jane', 'Kate'}

The update() method


The update() method will update a set with another iterable. Let’s say
you have two sets (Set1 and Set2) and you want to add objects from set2
to set1; you can use the update() method. In the example below, we are
trying to add objects from car2 to car1 using the update() method.
cars1 ={"Honda", "Suzuki", "Benz", "Tesla"}
cars2 ={'BMW', 'Toyota'}
cars1.update(cars2)
print(cars1)
Output:
{'Benz', 'Suzuki', 'BMW', 'Toyota', 'Tesla', 'Honda'}

The union() method


The union() method combines two sets to create a new set that contains
items from both sets.
cars1 ={"Honda", "Suzuki", "Benz", "Tesla"}
cars2 ={'BMW', 'Toyota'}
cars3 = cars2.union(cars1)
print(cars3)
Output:
{'Toyota', 'Honda', 'Suzuki', 'BMW', 'Benz', 'Tesla'}

52 | Page
The difference() method
If you have two sets and you want to know the difference between the
sets, you can use the difference() method. The difference () method
returns all the items that are not present in both sets. The code below
returns all the items that you cannot find in both the cars1 and cars2
sets. Tesla is not in the output because it is in both sets.
cars1 ={"Honda", "Suzuki", "Benz", "Tesla"}
cars2 ={'BMW', 'Toyota','Tesla'}
print(cars1.difference(cars2))
Output:
{'Suzuki', 'Benz', 'Honda'}

The intersection() method


The intersection() method returns items that are common in both sets.
It works the opposite to the difference() method. In our example below,
our code returns Tesla because it is in both sets.
cars1 ={"Honda", "Suzuki", "Benz", "Tesla"}
cars2 ={'BMW', 'Toyota','Tesla'}
print(cars1.intersection(cars2))
Output:
{'Tesla'}

These are the main set methods that you will encounter.

Frozen Sets
A frozen set is a set that does not support set methods that change a set.
You cannot add or remove items from the frozen set once you create one.
Any operation that attempts to change the contents of a set fails on a
frozen set. You can create a frozen set using the built-in function
frozenset().
animals = frozenset(('Lion', 'Tiger', 'Elephant'))
print(animals)
Output:
frozenset({'Lion', 'Elephant', 'Tiger'})

Use a frozen set if you want to keep the contents of your set unchanged.

53 | Page
Dictionary
A dictionary is a mapping data type. In a dictionary, keys are mapped to
values. Dictionaries are indexed by keys. Only immutable elements can
be dictionary keys. Dictionaries are insertion ordered (starting from
Python 3.6+). It remembers the order in which the keys are inserted.

Creating a Dictionary
Dictionaries have a pair of keys and values. The dictionary key and its
value are separated by a colon (:). The key is always on the left side, while
the value is always on the right side. The key and value pairs are
separated by commas. Here is an example of a dictionary:
dict1 = {"name": "Mary",
"school": "Yale",
"age": 22}
We can also create a dictionary using the built-in dict() function. Here
is how we would create the above dictionary using the dict() function.
dict1 = dict(name="Mary", school='Yale', age=22)
print(dict1)

Notice that with the dict() function, we do not have to use curly brackets.
When we print this out, the output will have curly brackets. See below:
Output:
{'name': 'Mary', 'school': 'Yale', 'age': 22}

In the above dictionary, "name" is the key, and "Mary" is the value.
Dictionaries can have duplicate values but not duplicate keys. Here is
what happens when we try to add the same keys to our dictionary. We
get a syntax error in the output because the key "Name" has been
repeated.
dict1 = dict(name="Mary", school='Yale', age=22, name='John')
print(dict1)
Output:
dict1 = dict(Name="Mary", school='Yale', age=22,
name='John')

^^^^^^^^^^^
SyntaxError: keyword argument repeated: name

54 | Page
Dictionary Keys
Remember, only immutable data types can be used as dictionary keys. A
list is mutable and cannot be used as a dictionary key. A tuple, a string,
integers, and floats can be used as keys because they are immutable.
Using a mutable object as a key will result in an unhashable error. See
below:
dict1 = {[9]: 1, 'b': 2, 'c': 3}
print((dict1))
Output:
dict1 = {[9]: 1, 'b': 2, 'c': 3}
^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unhashable type: 'list'

Accessing Dictionary Keys and Values


To access the values of the dictionary, we need to call the key. Let’s say
we want to access the value "Yale" in our dictionary. We will use the key
"school" to access the value.
dict1 = {"name": "Mary",
"school": "Yale",
"age": 22}

print(dict1['school'])
Output:
Yale

We can use the list() function to access all the keys in the dictionary.
With the list() function, you get a list of all the keys in the dictionary.
The syntax is list(dict). See below:
dict1 = dict(name="Mary", school='Yale', age=22)
print(list(dict1))
Output:
['name', 'school', 'age']

We can also access the dictionary values using a for loop (which we will
look at later). In the code below, we are using looping to access the
values in the dictionary. We can also do the same with the keys of a
dictionary.

55 | Page
dict1 = {"name": "Mary","school": "Yale", "age": 22}
for values in dict1.values():
print(values)
Output:
Mary Yale 22

The len() function returns the number of items that we have in the
dictionary. That is the number of key-value pairs in the dictionary. See
below:
dict1 = dict(name="Mary", school='Yale', age=22)
print(f'The number of key-value '
f'pairs in the dict is :\n{len(dict1)}')
Output:
The number of key-value pairs in the dict is:3

Dictionaries are Mutable


Dictionaries are mutable; we can add, delete, and replace values in a
dictionary. Let’s say we want to add Mary’s major to the above
dictionary. Here is how we do it. We will add the key "Major" and the
value "Finance." When we print the dictionary out, you can see that the
dictionary has been updated.
dict1 = {"name": "Mary","school": "Yale","age": 22}
# Adding another key-value pair
dict1['major'] = 'Finance'
print(dict1)
Output:
{'name': 'Mary', 'school': 'Yale', 'age':
22,'major':'Finance'}

We can also change the values of the dictionary. Let’s say Mary changes
her school and we want to update the dictionary with her new school.
We are going to access the key "school" and change its value. See below:
dict1 = {"name": "Mary","school": "Yale","age": 22}
# Changing dictionary value
dict1['school'] = 'Preston'
print(dict1)
Output:
{'name': 'Mary', 'school': 'Preston', 'age': 22}
If we want to change the dictionary keys, we can do it using the pop
method. Using the above dictionary as an example, let's say we want to
change the key "school" to "university." Here is how we do it.

56 | Page
dict1 = {"name": "Mary","school": "Yale","age": 22}
# Using pop to change key
dict1['university'] = dict1.pop('school')
print(dict1)
Output:
{'name': 'Mary', 'age': 22, 'university': 'Yale'}

We can also use the pop() method to remove a key-value pair from the
dictionary. Let’s say we want to remove the key "age" and its value "22"
from the dictionary below. Here is how we do it using the pop() method
(we will look at dictionary methods in detail later). You can see that the
output below does not have the key "age" and its value anymore.

dict1 = {"name": "Mary",


"school": "Yale",
"age": 22}
dict1.pop('age')
print(dict1)
Output:
{'name': 'Mary', 'school': 'Yale'}

Dictionaries are Ordered


Python dictionaries are insertion ordered. The dictionary remembers
the order in which the keys are inserted. When we print out the keys of
the dictionary below, the order of key insertion is maintained in the
output.
dict1 = {"name": "Mary",
"school": "Yale",
"age": 22}
print(dict1.keys())
Output:
dict_keys(['name', 'school', 'age'])

57 | Page
Merging Dictionaries
What if you have two (2) dictionaries and you want to merge them into
one? How do you do it in Python? Python 3 makes this task easy by
allowing us to use a bitwise OR operator (|). See the code below.
dict1 = dict(name="Mary", school='Yale', age=22)
dict2 = dict(sex="Female", country="Mexico")
dict1 = dict1 | dict2
print(dict1)
Output:
{'name': 'Mary', 'school': 'Yale', 'age': 22, 'sex': 'Female',
'country': 'Mexico'}

Using the | operator, we have added the content of dictionary 2 to


dictionary 1.
Here is another method or trick you can use to merge dictionaries. We
can merge dictionaries using the asterisk * operator. See the code below:

dict1 = dict(name="Mary", school='Yale', age=22)


dict2 = dict(sex="Female", country="Mexico")
# merging dictionaries using **
dict1 = {**dict1, **dict2}
print(dict1)
Output:
{'name': 'Mary', 'school': 'Yale', 'age': 22, 'sex': 'Female',
'country': 'Mexico'}

Dictionary Methods
Just like other data collection types, dictionaries also have methods.
Dictionary methods are just functions that we can perform on a
dictionary.
Dictionary Methods
1 pop () 6 clear ()
2 keys () 7 fromKeys ()
3 values () 8 update ()
4 items ()
5 get ()

58 | Page
The pop() method
We used the pop() method in our earlier example. It removes a specified
key and its value and can also be used to replace dictionary keys. This
pop method will always take one argument. If you do not pass an
argument, the method will return an error. The syntax is: dict.pop(key).

The keys() method


If you want to know the keys that you have in a dictionary, you can use
the keys() method. The keys() method takes no arguments.
dict1 = {"name": "Mary",
"school": "Yale",
"age": 22}
print(dict1.keys())
Output:
dict_keys(['name', 'school', 'age'])

The values() method


This one returns all the values that you have in a dictionary. It works
similarly to the keys() method. The syntax is: dict.values(). It takes no
arguments.

The items() method


The items method returns all the items in a dictionary. It returns a list
of tuples. Each tuple contains a key-value pair.
dict1 = {"name": "Mary",
"school": "Yale",
"age": 22}
print(dict1.items())
Output:
dict_items([('name', 'Mary'), ('school', 'Yale'), ('age',
22)])

The get() method


The get() method gets a specific value from the dictionary. It uses the
dictionary key to get the value. It takes one argument. Let's say we want
to get the name Mary from the dictionary; this is how we do it using the
get method.

59 | Page
dict1 = {"name": "Mary",
"school": "Yale",
"age": 22}
print(dict1.get('name'))
Output:
Mary

The clear() method


The clear() method clears your dictionary. It removes all elements and
leaves you with an empty dictionary.
dict1 = {"name": "Mary",
"school": "Yale",
"age": 22}
dict1.clear()
print(dict1)
Output:
{}

The fromkeys() method


This method creates a dictionary from a sequence of keys. The method
takes two arguments, an iterable and a value (optional). The items in the
iterable are converted into keys. The values are converted into values for
all the keys. If no value is given, the value of the dictionary becomes
None. Here is an example below:
keys = ("name", "school","age")
value = 'No-value'

dict1 = dict.fromkeys(keys, value)


print(dict1)
Output:
{'name': 'No-value', 'school': 'No-value', 'age': 'No-value'}

The update() method


If you want to add or update a dictionary with a key-value pair, you can
use the update() method. As an argument, the update method always
takes a pair of keys and values.You can add as many pairs as you want.
In the example below, we want to update our dictionary with new
information, so we use the update() method to add the key-value pairs.
Take note of the curly brackets inside the update method.

60 | Page
dict1 = {"name": "Mary",
"school": "Yale",
"age": 22}

dict1.update({'sex': 'Female', 'city': 'LA'})


print(dict1)
Output:
{'name': 'Mary', 'school': 'Yale', 'age': 22, 'sex': 'Female',
'city': 'LA'}

Nested Dictionaries
A nested dictionary is a dictionary that has another dictionary inside its
curly brackets. It is a dictionary inside another dictionary. Here is an
example of a nested dictionary. In the code below, we get the dictionaries
of three students, and we put them in one dictionary called "students."
When we print it out, you can see that it is a nested dictionary. There are
three dictionaries inside a dictionary.
john = {"name": "John", "grade" : "F"}
alison ={ "name" : "Alison", "grade" : "B"}
ben = {"name" : "Ben", "grade" : "C"}
# Creating a nested dictionary
students ={'student1': john, 'student2': alison, 'student3':
ben}
print(students)
Output:
{'student1': {'name': 'John', 'grade': 'F'}, 'student2':
{'name': 'Alison', 'grade': 'B'}, 'student3': {'name': 'Ben',
'grade': 'C'}}

Typecasting in Python
Typecasting is the process of converting a data type into another type
using a Python built-in function. When you are writing your code, there
will be times when you want to work with a different data type. For
example, you may have a floating number that you may want to convert
into an integer. You may have a string data type that you may want to
convert to a float or integer. Python has in-built functions that you can
use to change one data type to another. Below is a table of data types and
the in-built functions used in typecasting. These built-in functions only
take one element as an argument inside the parenthesis.

61 | Page
Data type In-Built Function Implementation
Integer int() a = int(a)
String str() b = str(b)
Boolean bool() c = bool(c)
Complex complex() a = complex(a)

Here is an example of typecasting in action. You can see from the output
that the class types of the elements have changed.
x = 2.5
# converting ax into an integer
x =int(x)
print(type(x))

num = 4
# converting an integer into a string
num = str(num)
print(type(num))

age = '20'
#converting a string into an integer
age = int(age)
print(type(age))

color = 'red'
#converting a string into a bool type
color = bool(color)
print(type(color))
Output:
<class 'int'>
<class 'str'>
<class 'int'>
<class 'bool'>

62 | Page
Chapter Summary
❖ Numeric data types in Python are integers, floats, and complex
numbers.
❖ Sequence data types are strings, lists, and tuples.
❖ Strings can be surrounded by single, double, or triple quotation
marks.
❖ String elements are indexed.
❖ Lists are enclosed in square brackets []; they are ordered and
mutable.
❖ Tuples are enclosed in round brackets(); they are ordered and
immutable.
❖ Sets are not ordered and they are surrounded by curly brackets.
❖ Typecasting is a method of converting data into another type using
in-built functions.
❖ A dictionary is a mapping data type in Python.
❖ You can merge dictionaries using the bitwise | and asterisk *
operator.
❖ Nested dictionaries are dictionaries that contain other dictionaries.

Challenges
1. Using slicing, write a code that prints out numbers 23-67 from the
following list.
a = [21, 34, 23, 34, 56, 67, 68]

2. Write a code that replaces the word "hate" with "love" in the
following string.
a = "I hate my bike"

3. Write a code to remove all duplicates from the following list.


list1 = [10, 20, 30, 30, 10, 40, 60, 70, 60]

4. Write a code to merge the two dictionaries below:


a = {'name': 'John','age': 36}
b = {'course':'Python', 'duration': '6 months'}
63 | Page
Chapter 3:
Operators in Python

64 | Page
3.Operators in Python
When you want to perform operations in Python, such as add, subtract,
divide, assign, and so forth, you can use Python operators. In this
chapter, we are going to look at the various operators that Python
provides.

Arithmetic Operators
Let’s start by looking at the different arithmetic operators that are
available in Python.

Addition Operator (+)


To add numbers in Python, we can use the addition operator (+). Below,
we are using the addition operator to add two integers.
a = 5
b = 6
#adding a and b using the addition operator
c = a + b
print(c)
Output:
11

We can also use the addition operator to concatenate (join) strings. In


the following code, we have two strings that we concatenate using the
addition operator.
x = 'My name is '
y = 'Carol.'
# concatenating two strings using the plus operator
name = x + y
print(name)
Output:
My name is Carol

The addition operator can also be used to concatenate two lists. See the
example code on the next page:

65 | Page
x = ["Name", False, 4, 4]
y = [1, 2, 3, 5]
# concatenating two lists
print(x + y)
Output:
['Name', False, 4, 4, 1, 2, 3, 5]

Subtraction Operator (-)


Subtraction can be performed using the subtract operator (-).
a = 6
b = 3
#subtracting b from a using the subtraction operator
c = a - b
print(c)
Output:
3

Multiplication Operator (*)


The Python operator for multiplication is the aristerisk * operator.
x = 5
y = 8
# multiplying x and y using operator
b = x * y
print(b)
Output:
40
Exponent Operator (**)
In high school math, exponential raises one number to the power of the
given number. We can perform this operation using the double asterisk
(**) operators. Let’s raise 3 to the power of 2 using Python code. The
code below is equivalent to 3 * 3.
x = 3
y = 2
b = x ** y
print(b)
Output:
9

66 | Page
The Division Operator (/)
In Python, to divide two numbers, you can use the divide operator (/).
The divide operator will always return a floating number (a number with
a decimal point). Note that our output below is a floating point number.
x = 6
y = 2
# dividing x by y using operator (/)
b = x / y
print(b)
Output:
3.0

The Floor Division Operator (//)


The floor division (//) is also a division operator but with a little twist.
Unlike the division operator (/) that returns a floating number, the floor
division will return a whole number. It always rounds down the
answer of the division to a whole number. This means that if the actual
division of a number is 3.7, the floor division will round it down to just
3. In the example below, we are using the division operator and the floor
operator, so you can note the difference between the two operators.

x = 8
y = 3
# using the division operator
b = x / y
print('The answer of division is ', b)

# using the floor division operator


b = x // y
print('The answer of division floor is ', b)
Output:
The answer of division is 2.6666666666666665
The answer of division floor is 2

67 | Page
The Modulus Operator (%)
The modulus (%) operator returns the remainder of a division. If a
division has no remainder, it should always return zero (0). The
following returns a zero, because when we divide 6 by 2, the remainder
is zero.
x = 6
y = 2
# using modulus to find the remainder
b = x % y
print(b)
Output:
0

Comparison Operators in Python


Another group of operators that we are going to dive into is comparison
operators. These come in handy when comparing objects.

The Equal Operator (==)


When you use the equal operator, you are stating that one element is
equal to the other one. In the code below, by using (==) between x and
y, we are stating that x is equal to y. Since x is not equal to y, our
expression returns a false value. See the code below:
x = 8
y = 3
a = x == y
print(a)
Output:
False

The Not Equal Operator ( != )


The exclamation mark next to the equal sign (!=) is the not equal
operator. The following expression will return true because x is not
equal to y.
x = 8
y = 3
a = x != y
print(a)
Output:
True

68 | Page
The Greater Than Operator (>)
This operator checks if the left value is greater than the value on the
right. When used, the operator will always return a Boolean value of
either true or false. In our code below, x (the left value) is bigger than y
(the right value), which is why we get a true output.
x = 8
y = 3
a = x > y
print(a)
Output:
True

The Less Than Operator (<)


The opposite of the greater-than (>) operator is the less-than (<)
operator. The less than operator checks if the left value is less than the
right value. Below, x is not less than y; that is why we get a false output.
x = 8
y = 3
a = x < y
print(a)
Output:
False

The Greater Than or Equal Operator (>=)


This operator checks if the value on the left is greater or equal to the
value on the right. It will always return a true value if one or both of the
conditions are true, and a false value if both of these conditions are false.
The expression below returns true because one of the conditions is true
(x is equal to y).

x = 3
y = 3
a = x >= y
print(a)
Output:
True

69 | Page
The Less Than or Equal operator (<=)
This operator checks if the value on the left is less than or equal to the
value on the right. Both conditions must be false to return a false value.
Below, x is not less than y, and x is not equal to y.
x = 4
y = 3
a = x <= y
print(a)
Output:
False

Membership Operators in Python


Membership operators check for the presence or membership of a value.
For example, you may write a code to check if a certain number is in the
list of numbers. The two membership operators are the in operator and
the not in operator. Let’s use code examples to see how this works. In
this code, we are checking if 2 is a member of the list x. Since 2 is in x,
our code outputs a true value.
x = [1, 2, 3, 4]
y = 2 in x
print(y)
Output:
True

We can also use the membership operators to check for items in strings,
sets, tuples, and dictionaries. Below, we are checking if the name
"Brian" is not in the string x. We get False because the name Brian is in
the string.
x = 'My name is Brian, I am learning Python'
y = 'Brian' not in x
print(y)
Output:
False

The in and not in operators are reserved keywords in Python. You


cannot use them as variable names.

70 | Page
Logical Operators in Python
When you encounter conditional statements in Python, you will also
encounter logical operators.

Operator Description
1 not Returns True if the condition is False
2 or Returns True if one of the conditions is true.
3 and Returns True if both conditions are true

The not Operator


The not operator reverses the results of an operand. If the expression is
true, it will return false. If it is false, it will return true. In the code below,
"not type (x)!= str" returns False because x is a string type. So, the
not operator reverses the false output and returns the true value. That
is why our output is true.
x = 'My name is Brian, I am learning Python'
print(not type(x) != str)
Output:
True

The or Operator
The or operator will return true if one or both conditions are true. The
code below returns true because one of the conditions is true (x ==10),
even though the other condition is false (x > 20).
x = 10
print(x == 10 or x > 20)
Output:
True

The and Operator


The and operator checks if all the conditions are true. If one of the
conditions is false, it will return a false value. In our example below, one
of the conditions is false (x > 20), so we get a false output.
x = 10
print(x == 10 and x > 20)
Output:
False

71 | Page
Identity Operators in Python
These operators are used to check the class type of a value. For example,
you can use the operators to check if an item is an integer or not (x is
type (int)). The operators will return "True" or "False."
Operator Description
1 is Determines if an object is a certain type
2 is not Determines if an object is not of a certain type
Using the is operator, we are checking if x is of the integer class. We get
False because x is not an integer but a list.
x = [2]
# checking if x is int
print(x is type(int))
Output:
False

Using the is not operator, we are checking if x is not of the integer class.
We get True because x is not an integer class but a list class.
x = [2]
# checking if x is not int
print(x is not type(int))
Output:
True

The Unpacking *Operator


In Python, we can use the asterisk operator (*) to unpack a list or a tuple.
Unpacking is simply assigning items from an iterable to multiple
variables. When you have multiple variables, one variable will be
assigned a single star (*). This is called a "starred expression." The
variable assigned the asterisk will take the items not explicitly assigned
to any other variable. Here is an example to demonstrate this.
names = ["John", 'Mary', "Lisa", "Peter"]

boy, *girls, boy1 = names


print(boy)
print(boy1)
print(girls)

72 | Page
In this code, we have three variables: boy, *girls, and boy1. Notice that
the girls variable is the "starred" one. The first variable (boy) will access
the first item in the list (John), and the last variable (boy1) will be
assigned the last item in the list (Peter). The "starred" variable (*girls)
will be assigned all the items not assigned to the boy and boy1
variables, and will return a list. See the output below.
Output:
John
Peter
['Mary', 'Lisa']

Unpacking a Dictionary using **Operator


We can use the double asterisk ** operator to unpack the values of a
dictionary using a function. The syntax is: func(**dict). Below, we use
the function to return the values in a dictionary. Notice that we
incorporate the **operator when calling the function.
def func(name, career):
return f'Name: {name}, Professional: {career}'

# Dictionary to unpack
dict1 = {"name": "Jennies","career": "artist"}
# Using the operator in the function call
print(func(**dict1))
Output:
Name: Jennies, Professional: artist

73 | Page
Chapter summary
❖ Arithmetic operators in Python are used to carry out arithmetic
operations.
❖ Comparison operators are used to compare objects in Python.
Comparison operators return a Boolean value.
❖ Membership operators check if an object is a member of a given
object.
❖ Logical operators are used for evaluating conditional statements.
They always return true or false.
❖ Identity operators are used for checking the class type of an object.
❖ The asterisk operator (*) is also known as the unpacking operator.

Challenges
1. Write a code that checks if the following number is even. Use the
modulus operator.

a = 24

2. Using the in operator, write a code that checks if the name Mark is
in the following string. Your code should return a true value if the
name exists and a false value if the name does not exist.

a = "One of the best students in our class is Mark."

3. What is the difference between the floor division operator and


the division operator?

74 | Page
Chapter 4:
Python Math

75 | Page
4.Python Math
In Python, you can perform so many math operations. Python math
operations range from the basic to the advanced. Let's dive into the
built-in math functions and other functions that come with the math
module.

Built-in Math Functions


Python math functions are built-in functions that are not imported
from the math module. We will look at the math module in the next
section. For now, let's dive into the built-in functions.

The sum() Function


Python has a function called sum() that sums or adds values in an
iterable. Here is the function in action below:
list1 = [1, 2, 5, 6, 7, 8, 9, 5]
add_list = sum(list1)
print(f'The sum of the iterable is {add_list}')
Output:
The sum of the iterable is 43.

In the above code, the sum() function goes over the list and adds up all
the values.

The abs() Function


The abs() function returns the absolute value of a number. Let’s say you
have a number with a negative sign (-56). The abs() function returns a
number without the negative sign.
a = -56
print(f'The absolute value of a is: {abs(a)}')
Output:
The absolute value of a is: 56

76 | Page
The min() and max() Functions
The min() function returns the iterable's smallest value.
list1 = [1, 2, 5, 6, 7, 8, 9, 5]
lowest_value = min(list1)
print(f'The lowest value in the list is '
f' {lowest_value}.')
Output:
The smallest value in the list is 1.

The max() function returns the largest value of an iterable.


list1 = [1, 2, 5, 6, 7, 8, 9, 5]
highest_value = max(list1)
print(f'The highest value on the list is '
f'{highest_value}.')
Output:
The biggest value in the list is 9.

The pow() Function


The pow() function is another built-in function in Python. The pow()
function returns a number to the power of the given number.
num = pow(2, 4)
print(num)
Output:
16

The above expression is equivalent to 2 * 2 * 2 * 2 (2 to the power 4).

The Math Module


Most math in Python is performed using the math module. The math
module is a library of math functions that we can use to perform math
operations. To use the math module, we have to import it. Most of the
operations that we have performed already can be performed with the
math module as well.
import math

77 | Page
math.sqrt
The first math.sqrt() function returns the square root of a number.
import math

num1 = math.sqrt(4)
print(f'The square root of a is {num1}')
Output:
The square root of num1 is 2.0

The math.sqrt() function will always return a floating number.

math. pow
The math.pow() function works similarly to the built-in pow() function.
It returns the power of a number. In the code below, it returns 4 to the
power of 2, or (4*4). The code below checks if pow() and math.pow()
are returning the same output given the same arguments. The output
confirms that the two are equal.
num1 = pow(4, 2)
num2 = math.pow(4, 2)
if num1 == num2:
print("num1 is equal to num2")
else:
print('num1 is NOT equal to num2')
Output:
num1 is equal to num2

math.ceil
Given a floating (decimal point) number x, the math.ceil() function will
round it to the nearest integer greater than x. For example, given 25.4,
the function will return 26. Here is the code to confirm that.
num = math.ceil(25.4)
print(num)
Output:
26

78 | Page
math.floor
The math.floor() function is the inverse of the math.ceil(). Given a
floating number x, math.floor() will round it to the nearest integer less
than x. For example, given 25.4, the function will return 25. Here is the
code to confirm this.
num = math.floor(25.4)
print(num)
Output:
25

math.fabs
Like the abs() function, math.fabs() returns the absolute value of a
negative number. Here is the function in action below.
num = math.fabs(-28.9)
print(num)
Output:
28.9

math.fmode
The math.fmode() function accepts two arguments (x and y). It then
calculates the remainder when x is divided by y. It works similarly to the
modulus operator (%). The only difference is that the math.fmode()
function will return a floating number.
num = math.fmod(6,2)
print(num)
Output:
0.0

The output is 0.0 because when you divide 6 by 2, you get no remainder.

79 | Page
Chapter Summary
❖ Built-in math functions in Python include the sum() function, abs()
function, and the min() and the max() functions.
❖ The math module has many functions that can be used in our code
to perform simple and advanced math.

Challenges

1. Write a code that finds the maximum of list a and the minimum
of list b and sums the two numbers.

a = [10, 20, 30, 30, 10, 40, 60, 70, 60]


b = [12, 45, 67, 88, 45, 34, 21]

2. Rewrite the code below using exponentiation.

a = (3*3*3*3 )/(2*2*2*2)
print(a)

80 | Page
Chapter 5:
User Input

81 | Page
5.User Input
Python has a built-in function that allows us to get input from users.
For example, we may want the users of our program to enter their
names, ages, and passwords. We can use the input() function to get
input from the user. The input() function returns a string.
# Getting a name from a user
name = input('Please enter your name:')
# Getting age from a user
age = input('Please enter your age:')
print(f'Your name is {name} and you are {age} old')

In the code above, using the input() function, we are asking the user to
enter their name and age. This code demonstrates how we can use the
input() function in Python.

Creating a Simple Calculator


Let's demonstrate how we can use the input() function in a simple
calculator app.
# Getting two numbers from a user
num1 = input('Enter a number')
num2 = input('Enter another number:')
total = num1 + num2
print(f'The answer is: {total}')

This simple calculator gets two numbers from a user and returns the
sum of the numbers. But this code will not work. Do you know why?
Think about it. Let's run the code and assume that the user inputs 12 for
num1 and 4 for num2. Here is the output of the code:
Output:
The answer is: 124
You can see from the output that the sum of 12 and 4 is 124, which is
wrong. It looks like the code has concatenated 12 and 4 to make 124. The
reason our code has done that is that the input() function will always
return a string.

82 | Page
So, input from the user is being interpreted as a string. If you check the
class types of num1 and num2, you will get a string. Since the inputs are
strings, the plus (+) operator concatenates the two strings. That is why
the output is 124. For the (+) operator to add num1 and num2, the two
inputs must be either integers or floats. We need to convert num1 and
num2 to integers. We use typecasting to convert our inputs from users
to integers. Here is how we do it:
# Getting two numbers from a user
num1 = int(input('Enter a number'))
num2 = int(input('Enter another number:'))
total = num1 + num2
print(f'The answer is: {total}')

In the code above, we have added the int() function to convert the user
input into integers. When we run the code, assuming that the user inputs
12 for num1 and 4 for num2, we get an output of 16.
Output:
The answer is: 16

Our code is now giving us the correct results.

Chapter Summary
❖ Python uses the in-built input() function to get input from users.
❖ The input() function returns a string.
❖ We can use typecasting to convert string output into a different data
type.

Challenge

1. Write a code that asks the users to input the numbers a, b, and c.
The code should multiply a by b and divide the answer by c. If a =
45, b = 30, and c = 10, your answer should be 135.0.

83 | Page
Chapter 6
Python Functions

84 | Page
6.Python Functions
In this chapter, we are going to dive into functions. A function is a block
of code that does something or performs a particular task. A function
only runs when it is called. Functions help in writing clean and concise
code by ensuring we avoid repeating code. If our code is not organized
into functions, we may have to repeat code in different areas of our
program. This breaks one of the most important rules of programming:
Don’t Repeat Yourself (DRY). By using functions, we avoid repeating
ourselves.

Creating Functions
To create a function, we use the keyword def. Every function has to start
with this word. If you see a line of code that starts with that word, just
know that it is a function. A function needs a name. The name of the
function comes after the def keyword. In the code below, the function
name is my_func. After the function name, we put parentheses () and a
colon (:). A function must do something, so our function below prints
out "hello world."
def my_func():
print('hello world')

# calling the function


my_func()
Output:
Hello world

Indentation in Functions
In functions, indentation is very important. Every line of code after the
def statement must be indented. Indentation tells Python that this line
of code is part of a function. In the code below, the whitespace preceding
the pass keyword is the indentation. If you don’t indent your function, it
will raise an error.

85 | Page
def my_func():
pass

indentation

The Pass Statement


You cannot create an empty function. Every function should have
content in it or it will generate an error. See below:
def my_func():
Output:
IndentationError: expected an indented block

The code generates an error because it expects content in the function


after the colon. If, for some reason, you want to create a function but you
don’t have content yet, you can add the pass statement. The pass
statement tells Python to do nothing. When we add it to the code above,
our program does not raise an error.
def my_func():
pass

Note that the pass statement is not exclusive to functions. It can be used
in other areas of Python code.

Adding Parameters and Arguments to Functions

Functions are powerful because we can add parameters to them. In a


function, parameters are added between the parenthesis.
def add_num(num1, num2):
sum1 = num1 + num2
print(sum1)
# calling the function
add_num(15,23)
Output:
38
Now, let's break down the code above; num1 and num2 are parameters
of the function. Parameters are placeholders for arguments. If a function
has two parameters, then it will require two arguments when called. The
function sums num1 and num2. When we call the function (when we
want to use the function), we have to pass arguments. In the code above,

86 | Page
we passed 15 and 23 as arguments. There is no limit to the number of
parameters that we can pass in a function.

Adding Default Arguments to Functions


We can add default arguments to a function. Default arguments are
arguments used by the function when we don’t pass any arguments. In
the code below, we have passed a default argument for parameter num2.
When we call the function and we do not pass any arguments for
parameter num2, it will use the default argument of 30. That is why we
are getting an output of 45.
def add_num(num1, num2 = 30):
sum1 = num1 + num2
print(sum1)
# calling the function
add_num(15)
Output:
45

If we pass an argument for num2, the function is going to ignore the


default argument of 30, and use the argument.

The Return Statement in Functions


When dealing with functions, you will encounter the return statement.
The return statement tells the function to stop the execution and store
the value. You can see the value stored by the return statement when
you call the function. The code below illustrates how we use the return
statement. When we call the function, it returns the sum of two
numbers, num1 and num2.
def add_num(num1, num2):
sum1 = num1 + num2
return sum1

# calling the function


print(add_num(15,16))
Output:
31

87 | Page
A function can have more than one return statement when it contains
conditional statements. In the code below, you can see that the function
has more than one return statement. It will return whatever condition
evaluates to true.
def max_num(a):
if a < 10:
return "Max is less than 10"
else:
return "The number is not less than 10"

print(max_num(12))
Output:
The number is not less than 10

Returning Multiple Values


Python makes it possible to return multiple values from a function. By
default, Python will return a tuple if more than one item is returned from
a function. We can then use unpacking to access the elements in the
tuple.
Below we have a function and we want to return two things: a list of
duplicates and a list of names called sasha from the list of names. We
have two values in our return statement – sasha and duplicates.
When we call the function, we get a tuple of lists as output—(['Sasha'],
['Sera', 'Sera']). We can access the lists in the tuple using unpacking. See
the code below:

88 | Page
def multiple_values(a: list):
duplicates = []
sasha = []
for name in a:
if a.count(name) > 1:
duplicates.append(name)
if name == "Sasha":
sasha.append(name)
return sasha, duplicates

names = ["Joseph","Nathan", "Sasha", "Sera",


"Muhammad", "Jabulani", "Patel", "Sera" ]

#Unpacking the function


sasha, duplicates = multiple_values(names)
print(sasha)
print(duplicates)
Output:
(['Sasha'], ['Sera', 'Sera'])
['Sasha']
['Sera', 'Sera']

The Yield Statement

Sometimes, while using functions, you will encounter the yield


statement. The yield statement works similarly to the return
statement. However, while the return statement returns a value to the
caller and stops the function, the yield statement generates a sequence
of values stored in a generator. Let’s demonstrate the difference
between the return statement and the yield statement using
examples.
Let’s say we want to get a sequence of values from a range. In the first
example below, we use the return statement. Notice that with the
return statement, only one value (zero) is returned, and every time we
call the function, we get the same value of zero. This is because the
return statement can only return one value at a time, and it will start
from scratch every time it is called, so it will always return the first
value. See below:

89 | Page
def func():
for i in range(4):
return i

num = func()
print(num)
print(num)
print(num)
Output:
0
0
0

The yield statement, on the other hand, returns a generator. Think of a


generator as a pack that contains all the values you have asked for. To
unpack the generator, we can use functions such as the next()
function. Unlike the return statement that starts from scratch every
time it is called, the yield statement stores everything in a sequence
and remembers the last value you got when you called the function.
Notice below that every time we call the function, it prints out the next
number in the sequence.
def func():
for i in range(4):
yield i

num = func()
print(next(num))
print(next(num))
print(next(num))
Output:
0
1
2

When you want to generate a sequence of items, use the yield


statement, and when you want to return just one value, use the return
statement.

90 | Page
Python *args and **kwargs
There are times when we do not know how many parameters to pass in
a function. In such circumstances, Python allows us to pass *args (Non-
keywords Arguments) as a parameter. With *args passed as a
parameter, we can pass as many arguments as we want. Using *args in
our function makes our function more flexible.
In the code below, we do not know how many numbers we need as
arguments for our function, so we use *args. Because we have used
*args, we can pass as many numbers as we want as arguments, and the
function will still work. Note that you can use whatever word you want
as an argument as long as you put an asterisk (*) at the beginning of the
word. However, it is good practice to use the letters args.
def add(*args):
print(sum(args))

add(12,23,34,56,78)
add(12,23,34)
Output:
203
69

We can also use the *operator to unpack an iterable when calling a


function with a *args parameter. Below, we pass a list as an argument to
the function by adding a "*" to the variable.
def add(*args):
return sum(args)

arr = [12, 23, 34, 56, 78]


# passing a list as argument using unpacking
print(add(*arr))
Output:
203

When you see **kwargs (keyword arguments) as a parameter, it


means the function can accept any number of arguments as a
dictionary (arguments must be in key-value pairs). See the
example below:

91 | Page
def myFunc(**kwargs):
for key, value in kwargs.items():
print(f'{key} = {value}')
print('\n')

myFunc(Name = 'Ben', Age = 80, Occupation ='Engineer')


Output:
Name = Ben
Age = 80
Occupation = Engineer

Type Hints
Python is a dynamically typed language. This basically means that you
are not required to declare a variable type before using it. Python only
checks the variable data type at runtime and the variable data type is
allowed to change. Other languages require the declaration of a
variable type before use. These are statically typed languages. For
example, if a variable is of an integer data type, it must be declared
before use (at compilation) and it will not be allowed to change. To give
Python a "statically typed feel", it allows us to annotate functions with
"type hints" at compilation. Here is an example below:
def translate(s: str) -> bool:
if s:
return True
else:
return False

Here we have a simple function. Notice that the function has one
parameter, s. The str after the s parameter is a "type hint." It simply
means that the function expects (or hints) that the argument that
should be passed for parameter s must be a string. If we expected the
argument to be an integer, we would use int instead of str. Notice the
-> bool at the end? This is another "type hint." It hints that it expects
the return of the function to be a Boolean value. Now, hints are not
enforced at runtime by Python; that means that if a non-string
argument is passed and a non-boolean value is returned by the
function, this function will run just fine. Type hints simply help to make
the code more descriptive and help programmers think statically. By
just looking at the hint annotations, a developer will know what type of
input and output data types are expected for the function.

92 | Page
Local and Global Scope in Functions
When you create a variable inside a function, by default the variable
can only be used in that function. If we try to use it outside of a
function, we will get an error. Below, we get a name error because
my_number is a local variable. It has a "local" scope, meaning that it is
only accessible inside a function.
def my_func():
my_number = 23

# printing the variable outside the function


print(my_number)
Output:
print(my_number)
NameError: name 'my_number' is not defined

Any variable created outside of a function is a global variable. It can be


accessed inside and outside of a function. In the example below, we can
use my_number inside a function even though it is outside the
function. This is because my_number is a global variable.
my_number = 23
def my_func():
return my_number

print(my_func())
Output:
23

When a variable is global, you cannot change or modify it inside a


function. If you try, your code will raise an error. Let’s try to change the
variable in our previous example inside a function. We are going to try
to add 5 to my_number (23).

93 | Page
my_number = 23

def my_func():
# modifying the variable
my_number = my_number + 5
return my_number

print(my_func())
Output:
my_number = my_number + 5
UnboundLocalError: local variable 'my_number' referenced
before assignment

Our code above is generating an UnboundLocalError when we try to


change a global variable inside a function. To modify a global variable
inside a function, we should use the global keyword inside our
function. We must declare the variable global before modification. We
are going to make changes to our code. Before modifying it, we are
going to declare the variable global. You can see from the output that
we have modified the global variable and our code has no errors.
my_number = 23

def my_func():
global my_number
my_number = my_number + 5
return my_number

print(my_func())
Output:
28

Functions are First-Class Citizens


In Python, functions are first-class citizens. Functions have similar
properties to other objects, such as floats, strings, and integers.
Functions have variable names. The whole function can be passed as
an argument to another function. A function can be passed to a list,
tuple, or set. Check the code below. We pass the whole function to the
variable x:

94 | Page
def func():
print('This is a function')

# Passing a function to a variable


x = func
print(x())
Output:
This is a function

Here is another example of a function using another function. Below


we have an upper_or_not function that gets a word from a user and
checks if the letters in the word are upper case or lower case. The
check function checks if a word is uppercase or not. The
upper_or_not function uses the check function in the conditional
statement (if check (word)). Basically, we have a function (check) that
has been passed to another function (upper_or_not), to be used by
that function. It’s properties like this that make functions first class
citizens.
def upper_or_not():
word = input("Please enter a word: ")
if check(word):
print('Word is in upper case')
else:
print('Word is in lower case')

def check(n: str):


if n.isupper():
return True
else:
return False

upper_or_not()

Functions can also be passed as arguments to higher-order functions


in Python. A higher-order function is a function that takes another
function as an argument. Let’s use the built-in sorted() function to
demonstrate this. The sorted() function takes another function as an
argument. Below, we create a function called sort_names. This
function is passed as an argument to the sorted() function. So
basically, we are using a function inside another function to sort a list
of names by the first name [0].

95 | Page
def sort_names(x):
return x[0]

names = [("John", "Kelly"), ("Chris", "Rock"), ("Will", "Smith")]

# sorting list of tuples using another function as key


sorted_names = sorted(names, key = sort_names)

print(sorted_names)
Output:
[('Chris', 'Rock'), ('John', 'Kelly'), ('Will', 'Smith')]

Functions can be passed as arguments to other functions. To


demonstrate this, we will write three functions. The first two functions
will be passed as arguments to the third function. Notice that when we
call the third function, it returns the results of the two functions. We are
basically using the third function to run the first and second functions.
# first function
def func1(n):
return n/2

# Second function
def func2(n):
return n*2

# Third function
def run(func, n):
return func(n)

# passing func1 as argument


x = run(func1, 6)
print("The ans to func1 is ", x)
# passing func2 as argument
y = run(func2, 6)
print("The ans to func2 is ", y)
Output:
The ans to func1 is 3.0
The ans to func2 is 12

96 | Page
Functions can also be used to return other functions. Basically, this is
what is called a nested function. A child function is contained within a
parent function. Below we have two functions — myfunc1 and myfunc2.
When we call the parent function, the child function gets returned.
def myfunct():
def myfunc2():
return 'I love Python'
return myfunc2()

x = myfunct()
print(x)
Output:
I love Python

Creating Decorators
Now that you have an understanding of how functions behave, we can
now dive into decorators. Everything that we have discussed above is
what makes it possible for functions to be used as decorators. So, a
decorator basically takes another function as an argument. The
decorator enhances the function without actually modifying it. It adds
extra functionality to the function. A decorator has a wrapper function
(parent function) and an inner function (child function). In the below
code, we are calling the decorator a wrapper because it wraps the
function it enhances or decorates. The wrapper function has one
parameter, func, because it takes one argument, the function it
decorates. When you use the decorator on another function, that
function is passed as an argument and then it is passed to the inner()
function of the decorator. In the code below, notice that the
used_inside_decorator function is passed as an argument inside the
wrapper function. When we call the used_inside_decorator function,
notice that the return from the inner function, "Decorated function
executed" is added to the output of the used_inside_decorator
function, "I run inside the inner function of the decorator". We
have two lines in the output. So, any functionality that is added to the
inner() function will enhance or improve the function that is being
decorated. So basically, that is how a decorator works.

97 | Page
# Decorator function
def wrapper(func):
# Inside the wrapper function is the
# inner function. This is where the function
# being decorated is passed as argument.
def inner():
# calling decorated function
func()
# This is what returns after function
# execution
return "Decorated function executed"
return inner

# Function to be decorated
def used_inside_decorator():
print("I run inside the inner function of decorator")

# Decorating function using wrapper function


used_inside_decorator = wrapper(used_inside_decorator)
print(used_inside_decorator())
Output:
I run inside the inner function of decorator
Decorated function executed

Now let’s modify the above code using the @ sign. When we use the @
sign on a function name, we are telling Python that we are creating a
decorator. So, in the code below, we precede the "wrapper" function
with the @ sign. We place the decorator right above the function we
want to decorate. See below:

98 | Page
# Decorator function
def wrapper(func):
# Inside the wrapper function is the
# inner function. This is where the function
# being decorated is passed as argument.
def inner():
# This is the decorated function
func()
# This is what returns after function
# execution
return "Decorated function executed."
return inner

# Decorating a function using @wrapper


@wrapper
def used_inside_decorator():
print("I run inside the inner function of decorator.")

print(used_inside_decorator())
Output:
I run inside the inner function of decorator.
Decorated function executed.

Adding Variables to the Decorator


So far, we have used decorators without passing any parameters to the
function being decorated. Now we are going to create a decorator that
decorates a function with parameters. Notice that the number of
parameters in the inner(a, b) function is equal to the parameters in the
summing(a, b) function. This decorator will have extra functionality that
will enhance the function it will decorate. The decorator will decorate the
summing() function. The summing() function sums variables a and b.
However, the decorator function will improve the function's
functionality by evaluating whether the arguments passed to the
summing() function are floats or integers. This is the power of
decorators; they enhance a function without permanently changing it.

99 | Page
# decorator function
def wrapper(func):
def inner(a, b):
if type(a)== int and type(b)== int:
print('a and b are integers')
else:
print("Either a or b is a float")
return func(a, b)
return inner

@wrapper
def summing(a, b):
c = a + b
print('The sum is ', c)

summing(12, 34.9)
Output:
Either a or b is a float
The sum is 46.9

Using a Decorator as a Timer


We can use a decorator as a timer function. Below, we are using the
decorator to measure the execution time of the range_tracker function.
The decorator enhances the range_tracker function by adding a timer
functionality to it. We import the timer module for this. We will talk
about modules later. We can now track how long it takes for the for loop
to create a list from a range. Here is the code below:

100 | Page
import time

def timer(func):
def inner():
start = time.perf_counter()
func() # range_tracker function sits here
end = time.perf_counter()
print(f'Run time is {end-start:.2f} secs')
return inner

@timer
def range_tracker():
arr = []
for i in range(10000000):
arr.append(i**2)

range_tracker()

Pure Functions
A pure function is a function that will return the same values given the
same arguments. A function is not pure if there is something outside
the function that can change its return value, given the same
arguments. We are going to use two examples to show this. Below is an
example of a pure function. Given the same arguments, this function
will always return the same output. It has no side effects. There is
nothing outside the function that can change its return value. For
example, the arguments that we have passed (12 and 45) will always
return 12.0.
def func(num1, num2):
x = (num1 * num2)/num2
return x
print(func(12,45))
Output:
12.0

The function below is not pure because the same arguments may
return different values. This is because it is using a variable outside the
function (global variable) – num3. If that variable changes, then given
the same arguments, the return will also change. So, the function is not
pure because it has side effects.

101 | Page
num3 = 10
def func(num1, num2):
x = (num1 * num2)/num2*num3
return x

print(func(12, 45))
Output:
120.0

Chapter Summary
❖ A function is a block of code that does something or performs a
particular task.
❖ A function is created using the def keyword. Every function requires
a name.
❖ You can add parameters to the function inside the parenthesis ().
❖ Function content should be indented.
❖ The return statement tells the function to stop the execution of the
function and store a value.
❖ The yield statement generates a sequence of values stored in a
generator.
❖ A variable declared outside of a function is a global variable; a
variable declared inside of a function is a local variable.
❖ Functions are first-class citizens with similar properties to other
objects in Python.
❖ Functions can be used as decorators.
❖ A function can either be pure or not pure.

Challenges
1. Write a function called list_average that takes a list of numbers
as an argument. The function should return the average of the
numbers in the list.

2. Write a function called join_string that takes one argument, a list


of strings. The function should join the elements of the string using
underscores (_). If we pass ‘love’ as an argument, your function
should return "l_o_v_e."

102 | Page
Chapter 7
Lambda Functions

103 | Page
7.Lambda Functions
In Python, normal functions start with a def keyword and are followed
by the name of the function. But there is another type of function that
does not need a name. It's a lambda function. A lambda function uses
the keyword lambda. Here is the syntax for a lambda function:

lambda arguments: expression


A lambda function can have many arguments but only one expression.
Here is an example of a lambda function.
lambda x, y: x*y

In the above code, x and y are the parameters. Everything after the
colon ":" sign is an expression (x*y). Take note that the function has no
name and the parameters are not surrounded by parenthesis. To run
this code, we have to provide arguments for x and y and surround them
with some parenthesis.
print((lambda x, y: x*y)(12, 13))
Output:
156

We have now passed some arguments to our lambda function and we


get the output. Note that even though it has no name, it behaves like
normal functions. It has to be called to return the results of the
expression. Note that the lambda function does not have a return
statement. If we were to use a normal function for the above code, here
is how it would look.
def multiply(x, y):
return x * y

print(multiply(12, 13))
Output:
156

104 | Page
Using Lambda Functions
Lambda functions are rarely used in isolation. They are usually used
with other functions. Lambda functions can be used with normal
functions.
def multiply(y):
return lambda x: x * y

a = multiply(20)
print(a(2))
Output:
40

The above function shows how we can use a lambda function with
normal functions. But the power of lambda functions is demonstrated
when they are used with other built-in functions such as filter(), map(),
and reduce(). Let’s see how we can use the lambda function with other
built-in functions.

Lambda with the filter Function


list1 = [20, 34, 67, 89, 77, 90]
# using lambda and filter to return numbers below 50
results = list(filter(lambda x: x < 50, list1)
print(results)
Output:
[20, 34]

We are using lambda with the filter() function to filter list1 to return
numbers that are below 50. Our output has returned a filtered list.

Lambda with the map Function


list1 = [20, 34, 67, 89, 77, 90]
# using lambda and map to divide numbers by 2
results = list(map(lambda x: x / 2, list1))
print(results)
Output:
[10.0, 17.0, 33.5, 44.5, 38.5, 45.0]

In the above code, you can see how the lambda function works with the
map() function to divide all the numbers in list1 by 2.

105 | Page
Lambda with the reduce Function
from functools import reduce

list1 = [20, 34, 67, 89, 77, 90]


results = reduce((lambda x, y: x + y), list1,100)
print(results)
Output:
477

In this code, we are using the reduce and lambda functions to sum the
list of numbers (list1). We then add 100 to the result of the sum.

Chapter Summary
❖ Lambda functions are nameless functions in Python.
❖ A lambda function can have many arguments but only one
expression.
❖ A lambda function can be used inside a normal function.
❖ A lambda function can be used with other higher functions such as
filter(), map() and reduce() functions.

Challenge
1. Using lambda and filter functions, write a code that returns all the
floating numbers from the list below:

List1 = [23.6, 50, 43.5, 63, 78.8, 99, 75]

106 | Page
Chapter 8
Conditional Statements

107 | Page
8.Conditional Statements
In conditional statements, code is only executed when a condition
evaluates to true. We tell the interpreter what to do if a condition is true
and what to do when a condition evaluates to false. In Python,
conditional statements start with the if keyword. This is why they are
sometimes called "if statements." Let’s look at a simple code that
illustrates the if statement.
a = 2
if a > 1:
print('a is greater than 1')
Output:
a is greater than 1

In this code, the if statement checks if a is greater than 1. If that


condition is true, we want the code to print out something. Since a is
greater than 1, the code prints out that a is greater than 1. If a was less
than 1, our code was going to print out nothing. That is because it can
only execute something when the condition evaluates to true. The if
statement will always have a colon ":" at the end. Note that all the code
that is part of the if statement is indented. The printed statement is
indented because that is how we tell the interpreter that it is part of the
if statement block. Your code will generate an indentation error if you
don’t indent that part.

Elif Statement
If we want our code to have multiple expressions or conditions, we can
use the elif statement. Elif is short for "else if." The elif statement will
come after the if statement. The elif statement is a block of code with
indented code after the colon (:).
a = -2
if a > 1:
print('a is greater than 1')
elif a < 1:
print('a is less than 1')
Output:
a is less than 1

108 | Page
We have now added more than one condition to our code. If the if
statement evaluates to false, our code will proceed to check the elif
statement. If the elif statement evaluates to true, that block of code is
executed. In our code, the elif statement evaluates to true; that’s why
we get "a is less than 1" output. You can add as many elif statements as
you want.

Else Statement
The else statement comes after the if statement and elif statement. You
tell the interpreter what to do if the if and elif statements check out to
be false.
a = 3
if a < 1:
print('a is greater than 1')
elif a == 1:
print('a is equal to 1')
else:
print('All the above conditions are false')
Output:
All the above conditions are false

109 | Page
Conditional Statements Flowchart

110 | Page
Nested If-Statements
A nested if statement is an if statement inside another if statement. Here
is an example below:
a = 2
if a > 1:
if a == 2:
print ("The number is 2 and it's greater than 1")
else:
print ("The number is not 2 but it's greater than 1")
else:
print ('a is less than 1')
Output:
The number is 2 and it's greater than 1

In this example, we have two if statements (one inside the other). The
first statement checks if a is greater than 1. If a is greater than 1 (if this
condition evaluates to true), it proceeds to the next if statement to check
if a is equal to 2. If not, it executes the "inside" else block. If a is less
than 1, then the outer statement will be executed. It will print "a is less
than 1."

Logical Operators in If Statements


We can use logical operators in our if statements to make them more
dynamic. The two logical operators are: and and or.
The and Operator
We can have two conditions in our if statement combined by the and
operator. Both conditions must be true for the block of code to execute.
See the code below.
a = 5
if a > 1 and a == 5:
print("The number is greater "
"than 1 and it's 5 ")
elif a > 1:
print("The number is greater "
"than 1 but it's not 5")
else:
print('The number is less than 1')
Output:
The number is greater than 1 and it’s 5

111 | Page
The if block will only execute if both conditions are true. If only one
condition is true, it will go on to the elif block. If the elif block evaluates
to false, it will execute the else block.

The or Operator
Using the or operator in our if statement means that it will execute if
one of the conditions evaluates to true. Below we have two conditions
in the if statement separated by the or operator.
a = 2
if a > 1 or a == 3:
print('a is either greater than 1 or it is 5')
else:
print('a is neither greater than 1 nor it is 5')
Output:
a is either greater than 1 or it is 5

Since the if block evaluates to true, that block of code is executed.

Shorthand Syntax
So far, all the conditional statements that we have written have taken up
more than one line of code. What if we could write everything in one
line? Writing everything in one line is the shorthand syntax that
improves code readability and makes code more concise. We can put
both if and else statements in one line of code.
a = 5
print('a is greater than 1')if a > 1 else print('a is less
than 1')
Output:
a is greater than 1

We can have multiple conditional statements using the short-hand


syntax. See below:
a = 5
print('Yes')if a > 1 else print('No') if a < 1 else print('')
Output:
Yes

112 | Page
Chapter Summary
❖ In conditional statements, a block of code only runs when a
condition evaluates to true.
❖ The first block of a conditional statement is the if statement.
❖ The else block is executed if the if statement evaluates to false.
❖ If you have multiple conditions, you can add the elif statement right
after the if statement.
❖ Nested if statements have if statements inside the if statement block.
❖ You can use conditional statements with logical operators such as
the and operator and the or operator.

Challenges
1. Write a function called odd_numbers. This function takes a list of
numbers as an argument and returns a list of odd numbers. Use list
comprehension.
list1 = [1, 2, 3, 5, 7, 9, 13, 17, 20]

2. Using condition statements, write a code that returns the number of


uppercase letters in the following string.
Str1 = "Mary Is Not in SchooL Today"

PS. If you struggle with these question, come back to them after reading the next chapter
(For loops)

113 | Page
Chapter 9
For Loops

114 | Page
9. For Loops
In Python, if you want to iterate over an iterable, you can use a for loop.
A for loop can iterate through any iterable – lists, sets, tuples, strings,
etc. A for loop starts with the keyword "for." A for loop creates a block
of code, so everything that is part of it is indented. A for loop will run
through an iterable until it reaches the end (unless it is stopped). Here
is an example of a simple for loop (keywords: for and in).
lis1 = [1, 3, 6, 7, 8, 9]

for numbers in lis1:


print(numbers)
Output:
1
3
6
7
8
9

Iterating over a String


A for loop can iterate over a string (a string is a sequence). Using a for
loop, we can print all the elements of the string, one at a time.
for letters in 'Python':
print(letters)
Output:
P
y
t
h
o
n

115 | Page
We can combine for loops with if statements (conditional statements).
Let’s say we want to iterate through a string to find the index of one of
the elements; we can combine a for loop with an if statement to iterate
through a string. Here is an example code below:
a = 'Python'
for letter in a:
if letter == 'h':
print(f'The index of the letter is:'
f'{a.index(letter)}')
Output:
The index of the letter is:3

Using the for loop and the if statement, we found the index of h in the
string. The index or position is 3.

Iterating over a Dictionary


A dictionary is another data type that we can iterate over using a for
loop. We can use a for loop to access the keys and values. Let’s create a
for loop that finds and prints out all the keys in a dictionary.
dict1 = {"Name": "Mary",
"School": "Yale",
"age": 22}
for keys in dict1.keys():
print(keys)
Output:
Name
School
age

We can also do the same for the values of a dictionary. See an example
below.
dict1 = {"Name": "Mary","School": "Yale","age": 22}

for value in dict1.values():


print(value)
Output:
Mary
Yale
22

116 | Page
If we want to return all the values and keys from the dictionary, then we
can use the for loop. See the code below:
dict1 = {"Name": "Mary",
"School": "Yale",
"age": 22}
for keys, values in dict1.items():
print(keys, values)
Output:
Name Mary
School Yale
age 22

Iterating through a Range


Python has a function called range(), which is a generator. This function
creates a sequence of numbers. By default, if you pass a number as an
argument to the range() function, you will get a sequence from zero (0)
to the number before the given number. It will increment the numbers
by 1 (by default). Let’s say you pass 5 as a number; the sequence will
range from 0 to 4. Using a for loop, we can unbundle the range sequence.
Notice from the output that 5 was not printed.
a = range(5)
for i in a:
print(i,end=' ')
Output:
0 1 2 3 4

You can also specify where you want the range to start, the increment
value, and where you want it to stop. The actual range syntax is
range(start, end, increment). Here is an example below:
for i in range(4, 20, 2):
print(i, end=' ')
Output:
4 6 8 10 12 14 16 18

117 | Page
The Break Statement
By default, a for loop will run through all the items in an iterable before
it stops. However, Python has a tool that you can use to stop a loop at a
specified position. This tool is the break statement. Let’s say you want
to iterate through a string but you want the iteration to stop at a certain
character. Here is how you use the break statement:
a = 'Python'
for letters in a:
if letters == 'h':
break
print(letters)
Output:
P
y
t

Using the break keyword, we are telling the interpreter to stop the
iteration once it finds h in the sequence. You can see from the output
that it only prints out the letters Pyt. Take note that the element h is not
printed out.

The Continue Statement


The continue statement tells the for loop that once it finds a specified
character in the sequence, it should stop the iteration, skip that
character, and start a new iteration.
a = 'Python'
for letters in a:
if letters == 'h':
continue
print(letters, end= ' ')
Output:
P y t o n

Notice how the element h, is skipped in the output?

118 | Page
Nested For Loops
A loop can have another loop inside it. This is called a nested loop. In a
nested loop, there is an outer loop and an inner loop. Check out this
example.
nested_list = [["Mazda","Mary"], ["Toyota", "John"],
["Isuzu", "Kelly"]]

#outer loop
for list1 in nested_list:
#inner loop
for item in list1:
print(item)
print('-----')
Output:
Mazda
Mary
-----
Toyota
John
-----
Isuzu
Kelly
-----

In this example, we are unpacking a nested list using a nested for loop.
The outer loop accesses the outer part of the list. The inner loop accesses
the inner parts of the list.
We can use nested loops to create a multiplication table. That’s the
power of nested loops. See the code on the next page.

119 | Page
#outer loop
for k in range(1, 10):
# inner loop
for j in range(1, 10):
x = k*j
print(x,end=' ')
print()
Output:
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81

List Comprehension and For Loops


You can create a list using a shorthand syntax that incorporates for loops
and if statements. This short syntax is called list comprehension. Using
list comprehension, we put everything into one line of code. The syntax
for list comprehension is:
x = [expression, member test in iterable, conditional statement]
The conditional statement is optional. Let’s write a program to
demonstrate list comprehension. Let's say we have a list of strings and
we want to return all the strings that start with the letter "a." Here is how
we do it using list comprehension. Notice how we have elegantly put
everything in one line. So, the first part [i for i] is an expression, [i in
a] is a membership test, [if i.startswith] is a conditional statement.
List comprehension makes our code more concise and readable. See the
code below:
fruits = ['Lemon', 'Orange', 'apple','apricot']

list1 = [i for i in fruits if i.startswith('a')]


print(list1)
Output:
['apple', 'apricot']

120 | Page
The Else Statement in For Loops
We can use the else statement not only with if statements but with loops
too. With the else statement, we specify what we want to happen after
the for loop is done iterating over a sequence. Below we have a function
that checks for a name in a given list. The for loop will check for the
name in the list. If the name is not in the list, we want the else statement
to be executed. The break statement will only stop the for loop if the
name is in the list. We have passed a list of names that does not have
Josh in it, so the else statement is executed in the output.
def checklist(names):
for name in names:
if name == 'Josh':
print("Josh is present")
break
else:
print('Josh is not in the list.')

checklist(['Peter', 'Mary', 'Derick'])


Output:
Josh is not in the list.

121 | Page
Chapter Summary
❖ A for loop is used to iterate over an iterable such as a set, list, string,
etc.
❖ A for loop will only stop once it reaches the end of the sequence.
❖ We can use a break statement to terminate or stop a for loop.
❖ We can use a for loop to iterate through a range.
❖ The continue statement stops the iteration and starts a new one.
❖ A nested loop has an outer loop and an inner loop.
❖ We can use the else statement with a for loop.

Challenges
1. Write a for loop to iterate through the list below. The for loop should
print out all the months except August. Make sure that your code
prints out everything horizontally.

months = ["June", "July", "August",


"September", "October"]

2. Write a code that prints out all the numbers in the list except 8 and
9:

num_list = [3, 7, 11, 9, 2, 4, 6, 8, 10]

3. Using a for loop, write a code that prints out the keys in the following
dictionary. However, your code should skip the key "school." It
should just print the "name" and "age."

dict1 = {"Name": "Mary",


"School": "Yale",
"age": 22}

122 | Page
Chapter 10
While Loops

123 | Page
10. While Loops
Another loop that Python has is the while loop. A for loop iterates
through a given sequence, but a while loop loops through a block of code
as long as the condition evaluates to true. A while loop will only stop
when the condition becomes false. A while loop starts with the keyword
while. Here is a simple while loop. In the code below, as long as a is less
than 4, the code will print out the word valid. It only stops when a is no
longer less than 4. We are incrementing a by 1 after each iteration. If we
do not increment, the code will run forever since the condition will
always be true.
a = 1
while a < 4:
print('Valid')
# incrementing a by 1 at each iteration
a += 1
Output:
Valid
Valid
Valid

The Break Statement


We can use the break statement to stop the loop even when the
condition is true. The break statement in the while loop works similarly
to the break statement in the for loop. Let’s take our previous example
and use the break statement to stop the loop before the condition
becomes false. In our previous example, the while loop printed out
"Valid" three (3) times. Now we want our statement to only print "Valid"
once. Here is how we do it using the break statement and the if
statement.
a = 1
while a < 4:
print('Valid')
if a == 1:
break
# incrementing a by 1 at each iteration
a += 1
Output:
Valid

124 | Page
The while loop stops after printing one "Valid" because of the break
statement.

The Continue Statement


The continue statement stops the iteration and begins a new one.
Similar to for loops, the continue statement tells the while loop that once
it finds a specified item, it should stop the iteration, skip that item, and
start a new iteration. This simple code illustrates how the continue
statement works. You can see that the number 3 is not in the output.
This is because once the while loop finds 3, it stops the iteration, skips
3, and starts a new iteration from 4.
a = 1
while a < 6:
a += 1
if a == 3:
continue
print(a)
Output:
2
4
5
6

The Else Statement


We can use the else statement in while loops. The else statement
specifies what should happen once the condition of the loop becomes
false. Here is a sample code on how we can incorporate it into our code.

a = 1
while a < 6:
a += 1
if a == 3:
continue
print(a)
else:
print("End of the loop")
Output:
2
4
5
6
End of the loop

125 | Page
Password Checker
Let’s create a simple password checker using a while loop. This code will
run until the user inputs the correct password. If the user inputs a wrong
password, it will prompt the user to try again. Once the user inputs the
correct password, they will be logged in. This is one way we can use while
loops. Run this code on your machine.
password = 'password1'
user_input = ' '
while user_input != password:
user_input = input ('Enter password :')
if user_input != password:
print("You have entered a wrong password. Try again")
else:
print('Logged in. Welcome')

Chapter Summary
❖ While loop executes a statement if a condition evaluates to true.
❖ The break statement terminates the loop even when the condition
is True.
❖ The continue statement stops the iteration and starts the new one.
❖ We can use the else statement with the while loop.

Challenges
1. Explain the difference between a while loop and a for loop.

2. Write a code that creates a list of even numbers from the user’s
input. The code should ask a user to input random numbers, but
only even numbers will be added to the list. Once the list has 4 even
numbers, the code should exit and return the list to the user. For
example, if the user enters 2, 5, 4, 6, 8, it should return [2, 4, 6, 8].
Write a function called even_num.

126 | Page
Chapter 11
Error Handling in Python

127 | Page
11. Error Handling in Python
What happens when your program encounters an error? In Python, an
error will stop your program from running. It will not run until the error
is handled. Three types of errors in Python are syntax errors, logical
errors, and exception errors. A syntax error occurs when there is an
error in the code and the interpreter does not understand it. A good
example of a syntax error is the missing colon ":" at the start of a code
block such as a function. You can correct a syntax error by making
changes to the code. A logical error occurs when there is a mistake in the
logic such that your code runs just fine. However, it produces incorrect
results. An example of a logic error would be using the wrong variable in
our code. The code may run fine, but the output will be wrong. Exception
errors occur when there is something wrong with our data and the
Python parser fails to execute the script. A good example of an exception
error is when we give our code a variable name that does not exist.
Exception errors can be handled in Python. We can expect them. Python
has in-built functions that handle these errors and keep our program
running.

Try and Except Blocks


Here is a simple error that we may encounter in our code.
x = 23
y = 0
ans = x/y
print(ans)
Output:
ans = x/y
~^~
ZeroDivisionError: division by zero

Our code is generating a ZeroDivisionError because we are trying to


divide a number by zero. We can handle this error using the try and
except functions. The basic structure of try and except is:
try:
pass
# You put your code in this block

128 | Page
except:
# You handle your errors here

We write our code in the try block, and we handle specific errors in the
except block. We can have as many exceptions as we want, depending
on the number of errors we want to handle. Let’s rewrite our previous
code that generated an error using the try and except blocks. Since we
are anticipating a ZeroDivisionError, we shall handle it in the except
block.
try:
x = 23
y = 0
ans = x / y
print(ans)
except ZeroDivisionError:
print('You cannot divide a number by zero')
Output:
You cannot divide a number by zero

We have handled our error using the try and except block. Our code is
no longer generating an error when it encounters a ZeroDivisionError;
instead it tells the user that they cannot divide a number by zero.
If we expect more errors, we can add more except blocks to our code.
Let’s say we want to get input from users and we expect that someone
will input a non-number into our code. We can add ValueError to our
exception block. See below:
try:
x = input('Enter a number:')
y = input('Enter another number: ')
ans = int(x) / int(y)
except ZeroDivisionError:
print('You cannot divide a number by zero')
except ValueError:
print('You have not entered a valid number')

The above code now handles ValueError. If an input is not a number,


our code will not crash; it will handle it.

129 | Page
The Else Statement
The else statement comes after the exception blocks. The else statement
specifies what we want to happen if there are no exceptions in our code.
We are going to continue with our example above. Let's modify our code
by adding the else block. The else block will return the results of the
division of those two numbers if there are no errors in the code.
try:
x = input('Enter a number:')
y = input('Enter another number: ')
ans = int(x) / int(y)
except ZeroDivisionError:
print('You cannot divide a number by zero')
except ValueError:
print('You have not entered a valid number')
else:
print(f'The answer is ,{ans}')

If x = 12 and y = 2, below will be the output of our code:


Output:
The answer is, 2.0

The Finally Statement


A finally statement comes at the end of the code. It specifies what we
want the code to do, whether the exception raised is handled or not. The
finally statement is not affected by errors raised in the try block that are
not handled. Below, we have a code that generates a ValueError that is
not handled in the except block. We ask the user to input numbers, and
we assume that the user inputs 18 for x and p for y. This generates a
ValueError.
Notice that even though our code generates an error, it still executes the
finally block (It still prints "Execution finished").

130 | Page
try:
x = input('Enter a number:')
y = input('Enter another number: ')
ans = int(x) / int(y)
except ZeroDivisionError:
print('You cannot divide a number by zero')
else:
print(f'The answer is :{ans}')
finally:
print('Execution finished.')
Output:
Execution finished.
ans = int(x) / int(y)
^^^^^^
ValueError: invalid literal for int() with base 10: 'p'

Now we are going to handle the ValueError raised in the code above
with an except block. Notice that the finally block is still executed even
when the error is handled.
try:
x = input('Enter a number:')
y = input('Enter another number: ')
ans = int(x) / int(y)
except ZeroDivisionError:
print('You cannot divide a number by zero')
except ValueError:
print('You have not entered a valid number')
else:
print(f'The answer is :{ans}')
finally:
print('Execution finished.')
Output:
You have not entered a valid number
Execution finished.

If the user enters valid numbers for both x and y (let’s assume the user
enters 18 for x and 9 for y), the code will generate an answer and still
run the finally block (See below code). In conclusion, the finally block
will run whether the exceptions raised in the code are handled or not.

131 | Page
try:
x = input('Enter a number:')
y = input('Enter another number: ')
ans = int(x) / int(y)
except ZeroDivisionError:
print('You cannot divide a number by zero')
except ValueError:
print('You have not entered a valid number')
else:
print(f'The answer is :{ans}')
finally:
print('Execution finished.')
Output:
The answer is :2.0
Execution finished.

Using the Finally Statement


The finally block should be used to execute something that you want
done at the end of a process. For example, if we want a file to be closed
whether an exception is raised or not, we can use the finally block. Here
is an example code:
try:
file = open('file.txt', 'w')
file.write(love)
finally:
file.close()
print('File has been closed')
Output:
File has been closed
file.write(love)
^^^^
NameError: name 'love' is not defined

The code above raises a NameError. If there is no finally block, this file
will not be closed until the error is resolved. But with the finally block,
this file will be closed whether the error is handled or not. This is an
example of how we can use the finally statement.

132 | Page
Chapter Summary
❖ Python errors will stop the program from running.
❖ We can use try and except blocks to test and handle errors.
❖ We can use the else block after the except block to specify what
should happen if there are no errors in our code.
❖ The finally block will always run whether the exception is handled
or not.

Challenge
1. Create a function called your_vat. The function takes no
parameters. The function asks the user to input the price of an item
and VAT (vat should be a percentage). The function should return
the price of the item after VAT. If the price is 220 and VAT is 15%,
your code should return a vat inclusive price of 253. Make sure that
your code can handle ValueError.

133 | Page
Chapter 12
Classes in Python

134 | Page
12. Classes in Python
Since Python is an object-oriented programming language, everything
is some kind of object. Python allows us to create objects using the class
statement.

Creating a Class
In Python, the blueprint for creating objects is by using the keyword
class. Below is an example of a simple class. Creating a class starts with
the keyword class, followed by the class name. We have created a class
called "Animals." This class has a variable or attribute called "home."
The variable is a property of the class.
class Animals:
home = "Zoo"

The class is not an object; it is simply a blueprint for creating objects. To


access the variable "home," we can create a class object. We can also
access it as a property of the class. See the code below:
class Animals:
home = "Zoo"
# Accessing variable as property of class
print(Animals.home)
# creating an object
x = Animals()
print(x.home)
Output:
Zoo
Zoo

Class Attributes
As you can see, the class that we have created above has one attribute
(home). Attributes are variables that belong to a class. This attribute is
called a class attribute. It does not belong to any specific object, but to
the class. This attribute has been created outside of a constructor.
Don’t worry if you don’t understand what a constructor is. You will
understand it by the end of this chapter.

135 | Page
class Animals:
# Class attribute
home = 'zoo'

Instance Attributes
Class attributes (variables) belong to a class and not to a specific object.
All objects in a class can access the class attributes. However, we can
also create instances that belong to a specific object. These attributes are
called "instance attributes." Instance attributes are created inside a
constructor. The constructor is the __init__() method. The
constructor initializes the instance attributes. The first parameter of the
constructor is self. The attributes of the instance come after "self". The
self parameter is used to access the attributes of the class objects. It
binds the attributes and methods to the class object (instance). It is not
written in stone that this parameter must be called self all the time. You
can call it whatever you wish, but it is good practice to call it "self." Let's
continue with the code from the previous section. We are going to add
instance variables to the class.
class Animals:
# class attribute
home = 'zoo'

def __init__(self, name, age):


# creating instance variables
self.name = name
self.age = age

The parameters in the constructor (__init__), "name" and "age" are


instance attributes. All the Animals class objects (instances) that we are
going to have in our class will have two attributes: name and age. This
basically means we have to pass arguments for "name" and "age" when
we instantiate class objects. The home variable is a class attribute. All
objects that will be instantiated will share this class attribute. The
difference between a class attribute (variable) and an instance variable
is that a class attribute can be accessed as a property of the class, while
an instance attribute cannot. If you try to access the instance attribute
as a class property, you get an attribute error. Below, we try to access the
variable "name" as a property of the class, and we get an AttributeError.
The "home" variable (a class attribute) does not return an error.

136 | Page
class Animals:
# class attribute
home = 'zoo'
def __init__(self, name, age):
# creating instance attribute
self.name = name
self.age = age

print(Animals.home) # Accessing class attribute using class


print(Animals.name) # Accessing instance attribute using class
Output:
Zoo
AttributeError: type object 'Animals' has no attribute 'name'

Class Instances
We have just looked at class attributes and instance attributes. Now, let's
look at instances. What are "class instances"? A class instance is an
object that belongs to a class. Let’s continue building our Animals class.
This time we are going to create two instances (objects). The object's
attributes will be name and age (instance attributes). Both objects will
share the same class attribute (color).
class Animals:
# class attribute
home = 'zoo'

# creating instance attributes


def __init__(self, name, age):
self.name = name
self.age = age
# creating Animals instances
animal1 = Animals("Lion", 4)
animal2 = Animals("Elephant", 6)

In the above code, we created two animal instances. The process of


creating instances is called object instantiation. We gave the objects
names: animal1 and animal2. Each instance has two attributes
(instance attributes): name and age. We have passed a name and age
as arguments for each object we have instantiated. For animal1, the
name is "Lion" and the age is 4. For animal2, the name is "Elephant"
and the age is 6. Both objects share the class attribute: home.

137 | Page
Now, here is how we can access the instance attributes of the objects that
we have instantiated. Let's say we want the attributes of animal1. Here
is how we do it.
print(animal1.age)
print(animal1.name)
print(animal1.home)
Output:
4
Lion
zoo

The bottom line is that you should use class attributes or variables for
data that is shared by all instances of the class. Use instance attributes
or variables for data that is unique to each instance.

Class Methods and Instance Methods


Let’s now look at class methods and instance methods. Class methods
are methods that are not bound to an instance of a class (object) but to
the class itself. Remember, there are two types of attributes in a class;
class attributes and instance attributes. Class attributes are bound to the
class, while instance attributes are bound to an object. Class methods
can only access and modify class attributes and not instance attributes.
There are two ways to create a class method. The first method is to use
the classmethod() function. The second method is to use the
@classmethod decorator. We are going to use the decorator to create
a class method for our class. The first parameter of this class method is
"cls". The cls keyword simply means referring to the class.
In our class below, there is a class attribute called "home." We are going
to create a class method that can modify this class attribute. In the code
below, we create a function called animals_home. Right at the top of the
function, we add the decorator @classmethod. This decorator
converts the function into a class method. We use this method to change
the class attribute home. We change the variable "home" from "Zoo" to
"Jungle." This shows that class methods can change class attributes. See
the code below:

138 | Page
class Animals:
# class attribute
home = 'zoo'

# creating instance attributes


def __init__(self, name, age):
self.name = name
self.age = age

# Creating a class method


@classmethod
def animals_home(cls, home):
cls.home = home

# creating Animals instances


animal1 = Animals("Lion", 4)
print(f'The Original animals home is a {animal1.home}')
# changing class attribute using class method
Animals.animals_home("jungle")
print(f'The new animals home is the {animal1.home}')
Output:
The original animals home is a Zoo.
The new animals home is the Jungle.

Now let's look at instance methods. Instance methods can access and
modify both class attributes and instance attributes. Similar to a class
method, an instance method is just a function in a class. It also starts
with the keyword "def". Its first parameter is the keyword "self". The
self parameter binds the method to the instance object. This makes it
possible for the method to access other methods and attributes of the
object and the class. In the code below, we have added an instance
method called insta_method. Notice that this insta_method has access
to the attributes of the object (name and age) and the class attributes
(home). Notice that we have changed the class attribute (home) value
from "Zoo" to "Jungle". When we print out the animal1 object, you can
see that the output for location says Jungle instead of Zoo.

139 | Page
class Animals:
# class attribute
home = 'Zoo'

# creating instance attributes


def __init__(self, name, age):
self.name = name
self.age = age

# Creating a class method


@classmethod
def animals_home(cls, home):
cls.home = home

# instance method
def insta_method (self):
# modifying the class attribute
self.home = "jungle"
return f'Name: {self.name}, Age: {self.age}, ' \
f'Location: {self.home}'

# creating Animals instances


animal1 = Animals("Lion", 4)
print(animal1.insta_method())
Output:
Name: Lion, Age: 4, Location: jungle

Instance methods are used more often than class methods. This is
because they can access and modify both class attributes and instance
attributes.

Static Methods
Unlike instance and class methods, static methods cannot access class
attributes or instance attributes. In Python, we create a static method
using a decorator. We write @staticmethod right above the method
we want to decorate. Static methods have no implicit first argument.
Neither cls nor self is passed as the first argument. Static methods are
just functions that you can call from the class or instance of the class.
Below, we have added a static method to our code. This method takes
one argument, which is the age of the animal, and checks if the animal
is an adult or not. Notice that we are using the animal instance
(animal1) to call the static method. Static methods are simply utility or
helper functions. They add extra functionality to a class without
accessing or modifying the class state.

140 | Page
class Animals:
# class attribute
home = 'Zoo'

# creating instance attributes


def __init__(self, name, age):
self.name = name
self.age = age

# Creating a class method


@classmethod
def animals_home(cls, home):
cls.home = home

# instance method
def insta_method (self):
# modifying the class attribute
self.home = "jungle"
return f'Name: {self.name}, Age: {self.age}, ' \
f'Location: {self.home}'

@staticmethod
def check_age(age):
if age > 5:
return 'Adult'
else:
return 'Not adult'
Output:
Name: Lion, Age: 4, Location: jungle
Not adult

Self in Classes
Let’s revist the "self" parameter once more. The "self" parameter refers
to the object. Simply put, "self" and "instance of the class" are the same
thing. How do we know that? Below, we check for the id of self and the
object that we instantiate. We get the same id. This proves that the two
are one object. See the code below:

141 | Page
class Animals:

def __init__(self, name):


self.name = name
print(f'The id of self is: {id(self)}')

# instantiating instance
obj = Animals("Lion", 9)
# checking the id of obj
print(f'The id of the object is :{id(obj)}')
Output:
The id of self is: 2058535766032
The id of the object is :2058535766032

To prove that self refers to an object, when we try to access an attribute


without instantiating an object, we get a "missing self" error.
class Animal:

def __init__(self, name):


self.name = name

def display(self):
return self.name

print(Animal.display())
Output:
TypeError: Animal.display() missing 1 required positional
argument: 'self'

The "missing positional argument" error is simply a missing object


error. Check what happens once we instantiate the object and we add
it to "Animal.display()."
class Animal:

def __init__(self, name):


self.name = name

def display(self):
return self.name
# instantiating instance
obj = Animal("Lion")
print(Animal.display(obj))
Output:
Lion

142 | Page
Deleting Class Objects
Python has a (__del__) method that is called when an object is being
deleted. This method is called a destructor. The __del__ method is
also called a finalizer because it finishes the delete process by ensuring
that there are no memory leaks. It basically releases resources that an
object was using. Below, we have one object — animal1. Once we use
del to delete animal1, the destuctor is called or invoked. Once we use
del on an object, all references to that object are destroyed. The deleted
object is now available for collection. When that happens, the
destructor is called, and we get the output of the destructor function.
Here is the code below:

class Animals:
# class attribute
home = 'Zoo'

def __init__(self, name, age):


# creating instance attributes
self.name = name
self.age = age

# Creating a class method


@classmethod
def animals_home(cls, home):
cls.home = home

# instance method
def insta_method (self):
# modifying the class attribute
self.home = "jungle"
return f'Name: {self.name}, Age: {self.age}, ' \
f'Location: {self.home}'

# Destructor
def __del__(self):
print("The object has been destroyed.")

# creating Animals instance


animal1 = Animals("Lion", 4)
# deleting object
del animal1
Output:
The object has been destroyed.

143 | Page
Inheritance
When you create a class, it has attributes and methods that belong to
that class. In Python, we can create another class that will inherit the
attributes and methods of another class. This is called inheritance. The
class that is being inherited from is called the parent class. The child
class inherits from the parent class. The child class will have the name
of the parent inside its parenthesis as a parameter. The animal class is
the parent class, and the dog class is the child class. In our code below,
the child class is inheriting the attributes (name and age) from the
parent class. The color attribute belongs to the child class only. Notice
that instead of writing the Dog class from scratch, we have inherited
attributes (name and age) from the parent class; this prevents code
repetition. Inheritance improves code reusability. We use the super()
function to inherit attributes from the parent class. The child class has
a method called dog_print that prints attributes of its instances. This
method is only available to the child class.
# Parent class
class Animals:
def __init__(self, name, age):
self.name = name
self.age = age

# Child class that inherits from the parent class


class Dog(Animals):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color

def dog_print(self):
return f'Dog name: {self.name}, color: {self.color}, ' \
f'age: {self.age}.'

# Instantiating object
dog = Dog('Kelly', 6, 'brown')
print(dog.dog_print())
Output:
Dog name: Kelly, color: brown, age: 6.

144 | Page
Polymorphism
Polymorphism is the second pillar of OOP (object-oriented
programming). Polymorphism means many forms. The below code
demonstrates the two pillars of OOP: inheritance and polymorphism.
The "Cars" class is the parent class; Tesla and BMW are the child
classes. Notice that all these three (3) classes have a method that has
the same name – the start method. Basically, polymorphism allows us
to give the same name to methods in parent and child classes.
Depending on which object is called, the other methods will be
overridden. So, when we instantiate the Tesla class object and call the
method, Python will recognize that we are not calling the Cars class
(parent) method, so it will override that method and only use the
method in the Tesla class (child class). This method starts a Tesla. If
we instantiate BMW and call the method, Python will override the Cars
(parent) and Tesla (child) methods and only use the method in the
BMW class.
class Cars:

def start(self): # Cars class method


return 'This method starts all cars'

class Tesla(Cars): # inheriting from the Cars class

def start(self): # Tesla class method


return 'This method starts a Tesla'

class BMW(Cars): # inheriting from the Cars class


def start(self): # BMW class method
return 'This method starts a BMW'

# Instantiating and printing cars object


car = Cars()
print(car.start())
# Instantiating and printing Tesla object
tesla = Tesla()
print(tesla.start())
# Instantiating and printing BMW object
bmw = BMW()
print(bmw.start())

145 | Page
In the example above, we have implemented polymorphism with
inherintance. However, it is possible to implement polymorphism even
when the classes are not explicitly linked.

Encapsulation
Encapsulation is putting data and its methods into a bundle or a unit
and making it inaccessible outside that unit. When you create a class,
the variables and methods that belong to that class are bundled
together into one unit. Basically, creating a class is the first step to
implementing encapsulation. So, the idea behind encapsulation is to
restrict access from outside a class. This protects the data from
accidental modification.

Public vs Private Members


Encapsulation makes data and methods private or protected from
outside ‘unit’ manipulation. We are going to use code to demonstrate
the significance of this. In the code below, we instantiate an object and
we assign "BMW" to that object as the brand. In the next line, we
overwrite the BMW by assigning "Ford" to the instance variable. When
we run print, you can see that the BMW has been overwritten by Ford.
This is because the brand variable is public and can be modified outside
of the class.
class Car:
def __init__(self, brand):
# class variables
self.brand = brand

# instance methods
def run(self):
return f'Please run {self.brand}'

# instantiating the object


car = Car("BMW")
print(car.run())
# Overwriting the instance variable
car.brand = 'Ford'
print(car.run())
Output:
Please run BMW
Please run Ford

146 | Page
To limit access to the data (instance variables), we can make the
variables private. In Python, we prefix the variable with double
underscores ("__") to make the data private so that it cannot be
modified outside of the unit. Below, we have made changes to the code
by adding a double underscore to the __brand variable. Notice that
when we try to overwrite BMW with Ford, like we did in the previous
example, it does not work. This is because the variable __brand is now
private and cannot be modified or changed from outside the class.
class Car:
def __init__(self, brand):
# Adding double underscore class variables
self.__brand = brand
# instance methods
def run(self):
return f'Please run {self.__brand}'

car = Car("BMW")
print(car.run())
# Overwriting the instance variable
car.__brand = 'Ford'
print(car.run())
Output:
Please run BMW
Please run BMW

To prove that we cannot access this variable outside the class, if we try
to print(car.__brand) outside the class, we get an attribute error.
class Car:
def __init__(self, brand):
# class variables
self.__brand = brand

# instance methods
def run(self):
return f'Please run {self.__brand}'

car = Car("BMW")
print(car.run())
# printing the underscore variable
print(car.__brand)
Output
print(car.__brand)
^^^^^^^^^^^
AttributeError: 'Car' object has no attribute '__brand'

147 | Page
If you do not want to make the data private, you can make it protected.
To make the variable protected, you only need to prefix the variable with
a single underscore '_'. However, protected data can be accessed and
modified outside of the class. Adding a single underscore tells other
programmers that use your code that the variable with an underscore
prefix is protected and should not be modified. Here is the naming
convention when it comes to encapsulation. See the code below:
class Car:
def __init__(self, doors, mode, brand):
# class variables
self.model = model # Public
self._doors = doors # Protected
self.__brand = brand # Private

148 | Page
Chapter Summary
❖ The class keyword is used to create objects in Python.
❖ We create a class using a keyword – class.
❖ Attributes are variables that belong to the class.
❖ The __init__ constructor is used to create instance attributes.
❖ An instance is an object of the class. A class can have many instances.
❖ Instantiation is the process of creating an instance of a class.
❖ A class method is a function inside a class.
❖ Deleting objects using del function will invoke the __del__() method
which will handle memory leaks.
❖ Inheritance is when a child class inherits the methods and attributes
of the parent class.
❖ Polymorphism allows us to give the same name to different methods
in the parent and child classes.
❖ Encapsulation is putting data and its methods into a bundle or a unit
and making it private.

Challenge
1. Write a code with three classes of cars – BMW, Tesla, and Toyota.
The three cars will have attributes – color, doors, and transmission.
The Tesla car will have one extra attribute — electric car (make this
a Boolean value). Use inheritance.

149 | Page
Chapter 13
File Handling

150 | Page
13. File handling
Working with Python, you will need to be able to open, read, write,
update, and delete files. Python has functions and libraries that we can
use to execute these operations. To operate with files, we use the Python
built-in open() function. The open() function works with several modes.
The syntax for the open() function is: open(filename, mode). The first
parameter is the name of the file, and the second parameter is the mode.
The main modes are in the table below:
Mode Operation
1 'x' Creates a new file, returns an error if the file exists
2 'w' Opens a file for writing, creates a file if it don’t exist
3 'r' Opens a file for reading
4 'a' Opens a file for appending

Creating Files
Let's say we want to create a file called "cars". We can use the open()
function with the x mode. Here is the code below:
file = open('cars.txt','x')
print(file)
Output:
<_io.TextIOWrapper name='cars.txt' mode='x' encoding='cp1252'>

You can see from the output that we have successfully created a file. The
txt at the end denotes the format of the file.

Writing Files
Now that we have created a file, let's write something to the file. We are
going to write the name of a car on the file. We are going to use the 'w'
mode for this operation.
file = open('cars.txt', 'w')
file.write('Tesla')
file.close()

151 | Page
So, the code above opens the file that we created, and since we are using
the mode 'w', we write something onto the file. We have written the car's
name on the file. Now let's read the file.

Reading Files
We can now open the file to read its contents using the 'r' mode. If you
try to open a file that does not exist, it will return an error.
file = open('cars.txt','r')
print(file.read())
file.close()
Output:
Tesla

You can see from the output that we have successfully opened and read
the content of the file. We can also open the file using the readlines()
method and specify which lines to read if a file has many lines
(file.readlines).
Note that if we had opened the file without specifying the mode 'r', we
would still be able to read the file. This is because ‘r’ is the default mode.
See below:
file = open('cars.txt')
print(file.read())
file.close()
Output:
Tesla

Appending Files
Now that we have a file with content on it, what if we want to add more
content to it? What do we do? We open the file in append mode ('a').
Note that if you open a file in append mode and that file does not exist,
it creates a new file. We are going to add another car name to the file,
and then we will open and read the file.
file = open('cars.txt','a')
file.write('\nBMW')
file.close()

We have opened the file and we used the write() method to append a
new line to the file. We can also use the writelines() method for this. We
are also using the escape character (n) to tell Python to append the new

152 | Page
content on a new line. If we don’t use the escape character, the write()
method appends the content on the same line as the previous content.
Now, let's open the file in "r" mode to check the content.
file = open('cars.txt','r')
file = file.read()
print(file)
file.close()
Output:
Tesla
BMW

The output shows that we have successfully appended BMW to our


cars.txt file.

Closing Files
Notice that every time we open the file, we use the close() method at the
end. When you are done using the files, you must close them. That frees
up resources that were allocated to the file.
file.close()

Using the With Statement


There is a better way to open, read, append, and write files. We can use
the with statement. The with statement creates an indented block of
code that executes the code. The with statement closes the file for us, so
we don’t have to use the close() method at the end of the file operation.
Let us open our previous file in "w" mode, add another car name to it,
and read its contents using the with statement.
# appending text to file
with open('cars.txt','a') as file:
file.write('\nHonda')
# reading the file with open
with open('cars.txt', 'r') as file:
print(file.read())
Output:
Tesla
BMW
Honda

153 | Page
Using the with statement, we have appended a new line to our file and
read its content. Notice we didn’t use the close() method because the
with statement closed the file for us.

Deleting Files
How do we delete files using Python? If we want to get rid of a file that
we have created, we need to import a module. We will talk about
modules in the next chapter. This module has in-built functions that
we can use to delete files. The module is called OS (short for Operating
System). It is used for operating system-dependent functionality. Let's
write the code that deletes a file. I will explain what the code does.
import os
os.remove('cars.txt')

The module OS has a remove() method that we can use to delete the
file. This will generate an error if the file does not exist. To get around
that, we should use the OS module to first check if the file we want to
delete exists. See the example below:
import os
os.remove('cars.txt')

if os.path.exists("cars.txt"):
os.remove('cars.txt')
else:
print('No such file exist'

In our code above, if the file does not exist, the else statement will be
executed. This is a much safer method of deleting a file.

154 | Page
Chapter Summary
❖ Python has a built-in function called open() that we can use to open,
read, and write files.
❖ We can open files in different modes—create, write, and append.
❖ It is important to close files when we are done using them to free up
resources.
❖ The best practice is to use the with statement when working with
files.
❖ The os module’s remove method is used to delete files.

Challenges
1. Create a file called names.txt. Write the four names from the list
below on to your file. Each name should be on a different line. Make
use of the with statement.

names = ["John","Mary","John","Peter"]

Write another code to read the file you just created.

2. Open the file you created in question 1 and add another name to it.
The name should be on a separate file. Add the name "Salah" to the
file.

3. Delete the file you just created using the OS module.

155 | Page
Chapter 14
Modules and Pip

156 | Page
14. Modules and Pip
The Python language becomes even more powerful once we start using
modules. Modules not only make the language powerful but also make
it easy for programmers to organize their code. Modules help create
clean and reusable code. In the previous chapter, we saw how we could
use a module OS to delete files. What is a module? A module is a Python
file that contains Python code that can be imported and used in another
file.
Creating a Module
To create a module, we simply add functions to a file and save it with a
.py extension. We are going to create a module.
class Multiplication:
def __init__(self):
self.num1 = input('Enter a number:')
self. num2 = input('Enter another number:')
# Creating a class method
def multiply(self):
return int(self.num1) * int(self.num2)

# instantiating object
ans = Multiplication()
print(f'The answer is : {ans.multiply()}')

We have created a simple class that multiplies two numbers, num1 and
num2. We are going to save this as multiply.py. That’s it. We have
created a module. We can now use this module in another file. Run this
code and pay attention to how it works. Now, to use this module in
another file, we have to import it. We create a new Python file in the
same folder where we saved our multiply.py file. Notice that to import,
we use the name of the file we saved.
import multiply

x = multiply.Multiplication()
print(f'The answer is :{x}')

157 | Page
By importing the module, we have imported its functionality. When we
run print(x), the code asks us to input two values, num1 and num2. Take
note of how short our code is just because we are using a module. Let’s
say we enter 12 for num1 and 12 for num2, our print(x) function will
return:
Output:
The answer is: 144

Importing Modules
We can import modules using their names, as we did in our previous
section. But sometimes the module name can be so long that we may
want to shorten it in our code. Python allows us to create another name
for our module when we import it. In our previous section, we imported
our module multiply as multiply. We could shorten the name at
importation by creating an alias. See below how we can do it.
import multiply as mt

x = mt.Multiplication()
print(x)

We imported multiply as mt, and it works fine. When working with


modules in Python, it is best practice to shorten the names of some
modules upon import. Below is a list of some of the most popular
modules in data science and how they get imported into files.
Modules How they are imported
1 pandas import pandas as pd
2 numpy import numpy as np
3 matplotlib import matplotlib.pyplot as plt
4 seaborn import searborn as sns

Python Pip
You will have to install on your machine most of the modules that you
are going to want to use, because they do not come pre-installed with
Python. For example, to use the pandas module, it must be installed on
your system. Python uses a package called Pip to install modules on your
machine. If you want to install Pandas, NumPy, Matplotlib, and other
modules, you will have to use pip. Pip comes preinstalled with Python.
158 | Page
You can visit the pip website for how you can install and run pip on your
machine. https://pypi.org/project/pip/

Using Modules: random


Let's use some of the in-built modules in Python. One popular module
is the random module. Below is a code that demonstrates how we can
use the random module.
import random

# generating a random int between 0 and 10


number = random.randint(0, 10)
count = 0
# checking if the condition is true
while True:
guess = int(input('Enter a number: '))
if guess != number:
# incrementing count by 1 for every iteration
count += 1
if count < 3:
print('Try again')
else:
print('You have run out of guesses. You lose.')
break
else:
print('You guessed right. You have WON!!!')
break

In the above code, we have imported the random module. Using the
random method, randint(), we are generating a random integer
between 0 and 10. We then ask the user to guess the number. The count
variable keeps track of how many attempts the user has made. The user
gets three (3) attempts to guess the correct number. After three (3)
wrong guesses, the program exits. This is an example of how we can use
in-built modules in our code.
If you want to know the current version of your Python interpreter, you
can use the sys module.

159 | Page
import sys
x = sys.version
print(x)
Output:
3.11.0b1 (main, May 7 2022, 22:58:47) [MSC v.1931 64 bit
(AMD64)]

Using Modules: flask


If you want to go into web development with Python, you will have to
learn to use flask. Flask is a Python module used to build web
applications. We are going to build a simple app using the flask
module.Unlike the random module that comes pre-installed with
Python, the flask module must be installed on our machines. To install
flask using pip, run pip install flask from the command line or
terminal. When you start working with Flask for your projects, it is
recommended that you install it in the virtual environment (not
covered in this book). Once you install it, import Flask. See the code
below.
From flask import Flask # importing the flask module.
app = Flask(__name__) # instantiating Flask app
@app.route(‘/’) # Decorator to route the function below
def home():
return ‘<h1>My First Flask App</h1>’

if __name__==”__main__”:
app.run() # running app on local server

So, the first thing we did was import the module. Then we instantiated
an app from the Flask class. The __name__ variable simply means the
app is being run in the current module (main file and not imported).
The @app.route ('/') is a decorator that will open the home URL ('/'),
and return the information in the home function. The if
(__name__=="__main__") is simply telling Python that if this
module is the main file and not imported, run the app.
When you run the app, you will get the output above. Take not of the
last part which gives you the address at which your app is running
(http://127.0.0.1:500).

160 | Page
Output:
* Serving Flask app 'App' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a
production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000 (Press CTRL+C to quit)

When you copy this address and paste it into your browser, you will get
the page below:

Using Modules: pandas


If you are interested in data science or data analysis, then you will
encounter the pandas library. The pandas module is one of the most
widely used libraries in data analysis and data science. We are going to
demonstrate how you can create a data frame using the pandas
module. First, you will have to install pandas on your machine using
"pip install pandas". To use pandas, import it into your script.
Below, we have three (3) lists: brands, models, and year. Using the
pandas DataFrame class and the zip() function, we create a DataFrame
that combines the three lists into a table. See the code below:

161 | Page
import pandas as pd

brands = ['BMW', 'Tesla', 'Honda']


models = ['X6', 'X', 'Civic']
year = [2016, 2015, 2012]

# Creating a DataFrame using Pandas


df = pd.DataFrame(zip(brands,models, year),
columns=[ "Brands", "Models", "Year"])

print(df)
Output:

162 | Page
The Zen of Python
The Zen of Python is a list of guiding principles (best practices) for
writing Pythonic code. This list was compiled by Tim Peters and was
later added to the Python library. You can access the Zen of Python
using:
import this

print(this)
Output:
The Zen of Python, by Tim Peters

Beautiful is better than ugly.


Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do
it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

The Help Function


The Python help() function is a built-in function that provides
documentation for Python functions, objects, modules, keywords, and
so forth. Let's say you want to know about Python classes; you can just
pass the class as an argument to the function and it will return the
Python official documentation on classes. Run the function below to
see the output.
print(help('class'))

Let's say you want help with Python dictionaries. You can simply pass
the dict keyword as an argument to the help function.

163 | Page
print(help(dict))

You can do this with your variables too. Just pass the variable as an
argument. Run this code below.
a = 'str'
print(help(a))

Chapter Summary
❖ A module is a Python file that contains Python code that can be
imported and used in another file.
❖ All Python modules have a .py extension.
❖ We can use the keyword import to import modules.
❖ Pip is a package manager for Python modules.

Challenges

1. Write a code that returns all the Python reserved keywords.

2. Using the pandas module, create a dataframe from the dictionary


below. The dataframe should have two columns: Brand and Model.

cars = {"BMW": "X6","Tesla": "X", "Honda": "Civic" }

164 | Page
Chapter 15
Time and Date

165 | Page
15. Time and Date
Python has two modules that we can use to work with time. In this
chapter, we are going to explore the time module and the datetime
module.

The Time Module


To work with the time module, we have to import it first.
import time

When dealing with the time module in Python, you will have to
understand what the epoch is. The epoch is the point where time starts
and is platform-dependent. Here is how you find the epoch for your
platform using the time module:
import time

print(time.gmtime(f))
Output:
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0,
tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
So, if you're using Windows or another operating system like Linux, the
current epoch began on January 1, 1970.The time module measures time
from the epoch. It returns a floating-point number.

The time.time() method


When you use the time module to check your current time, it will return
the seconds after the epoch; which is the current time in seconds. Here
is the code below:
import time

print(f'The current time in seconds since the epoch is:'


f'{time.time()}')
Output:
The time in seconds since the epoch is:1642862429.4562538

166 | Page
One way we can use the time.time() method is to measure how long it
takes to run our code. Yes, we can use it as a timer. Here is the
implementation below:

import time

start = time.time()
for i in range(200000000):
i*2
if i == 10:
time.sleep(20)
end = time.time()
elapsed = end - start
print(f'The time taken to run this code is '
f'{elapsed:.2f} seconds')
Output:
The time taken to run this code is 61.50 seconds.

The above code checks how long it takes to loop through a range and
multiply each element by 2. The start variable returns the time at the
start of the code execution. The end variable returns the time at the end
of the execution. The difference between the two is the time it has taken
for the loop to loop over the range. The time.sleep() function in the loop
tells the loop to pause or sleep for 20 seconds once it finds 10 in the
range.

The time.ctime() method


The time.ctime() module returns a 24-character string representing the
local time. This is the time since the epoch. Here is the code below to
show that.
import time

now = time.ctime()
print('Current time is',now)
Output:
Current time is, Sat Jan 22 23:04:47 2022

167 | Page
The time. localtime() method
To get the current time, we can use the time.localtime() function. The
time.localtime() returns your current local time.

import time
print(f'The time now is:'f'{time.localtime()}')
Output:
The time now is:time.struct_time(tm_year=2022, tm_mon=1,
tm_mday=22, tm_hour=18, tm_min=5, tm_sec=36, tm_wday=5,
tm_yday=22, tm_isdst=0)

The above time is a bit hard to read. We can format it using the asctime
method. Here is how we add to the code:
import time

print(f'The time now is '


f''f'{time.asctime(time.localtime())}')
Output:
The time now is Sat Jan 22 18:31:07 2022

You can see now that our time is now more readable. The asctime
method returns a 24-character string.

Other time methods


Time Functions
1 time.sleep() Used to halt the execution of a code for a given number of seconds.
2 time.gmtime() Returns struct_time UTC. Takes seconds since the epoch as the argument.
3 time.sftrtime() Used to format time strings
4 time.strptime() Converts a time string into a struct_tme object
5 time. asctime() Takes a struct_time and returns a string of 24 characters.
6 time.mktime() Returns seconds passed since the epoch. It takes struct_time or 9
characters tuple as an argument.

168 | Page
The timeit Module
We saw earlier how we can use the time.time() function to check code
execution time. We can also use the timeit() method to check the speed
of code execution. The timeit function takes a code as a parameter. The
code should be in string format.
import timeit

code = """

for i in range(2000000):
print('')
if i == 10:
time.sleep(20)
"""
time_elapsed = timeit.timeit(code, number=1)
print(f'The code execution time is'
f'{time_elapsed:.2f} seconds')
Output:
The code execution time is 45.93 seconds

The time elapsed is the time taken for the loop to iterate through the
range.
The datetime Module
Another module in Python that you will find very useful is the datetime
module. The datetime module comes pre-installed with Python. The
module contains most of the functionalities that you will need for time
and date objects in your code. To work with the datetime module, we
have to import it.
import datetime

The now() method


The now() method of the datetime class returns the current local date
and time. Here is the code to demonstrate the method .
import datetime
time_now = datetime.datetime.now()
print('The time and date now is', time_now)
Output:
The time and date now is 2022-01-23 15:21:24.884840
The now() method uses Greenwich Meridian time by default.

169 | Page
The date() method
We can use the date() method from the datetime module to create a
date object. The date() method takes three parameters: year, month,
and day.
import datetime
date_object = datetime.date(2022,1,23)
print('The date I just created is', date_object)
Output:
The date I just created is 2022-01-23

The today() method


To get the current date, we use the today() method of the datetime class.
This method is in the date class. Here is how the code looks:
import datetime

today = datetime.date.today()
print('Today is', today)
Output:
Today is 2022-01-23

The strftime() method


The strftime() method allows us to format the date and time to our
specifications. Sometimes we don’t want the whole date object, but just
the year and month. We can use the strftime() method to achieve that.
The now() method that we used above returns the date, the hour,
minute, and seconds. Using the strftime() method, we can return only
the part of the string that we want. Let's say we only want the hour and
minute parts of the string; here is how we do it using the strftime
method:
import datetime

time_now = datetime.datetime.now()
print('Time now is', time_now.strftime('%H:%M'))
Output:
Time now is 22:17

Using the %H and %M format codes, we can return only hours and
minutes from the now() method. There are many format codes that you
can use (look them up online). Let's look at another example.

170 | Page
date_object = datetime.date(2022,1,23)
print('The Month is', date_object.strftime("%B"))
Output:
The Month is January

In the above code, we want to return only the month from our date
object, so we use the %B format code, and we get January in the output.
Take time to explore the many other format codes that you will find
online.

Chapter Summary
❖ The time module and datetime module are used to handle time in
Python.
❖ The epoch is the starting point of time. The current epoch started at
midnight on January 1, 1970, UTC.
❖ The time module provides different ways to work with time in code.
❖ The datetime module is used to work with and manipulate date and
time objects.

Challenge
1. Create a function called your_age. The function should ask the
user to enter their year of birth and should return their age. For
example, if the user enters 1990 as the year of birth, the function
should return "You are 32 years old." The user should only enter a
4-digit year. If a user enters a number with more than or less than 4
digits, tell the user to enter a valid number. The user cannot enter
the current year or the year after the current year as a year of birth.
If the user enters an invalid year, tell the user to enter a valid year.
The function should run until a valid year of birth is entered.

171 | Page
Answers to Challenges

172 | Page
Chapter 1
1. In Python, a comment is preceded by a hash sign (#). A docstring
begins with triple quotes (""") and is closed by another (""") triple
quote. "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.
2. To assign multiple variables to a single value we use the equals sign
(=) between the variables. You can see below that both x and y have
the same value of 23.
x = y = 23
print(x,y)
Output:
23 23

3. Python is case-sensitive, so variable num is not equal to variable


Num. In the code below, we get a NameError when we try to print
num as Num because they are different.
num = 23

print(Num)
Output:
print(Num)
NameError: name 'Num' is not defined

173 | Page
Chapter 2
1. Since lists are indexed (each item has a position), it is possible to use
slicing to access the items in the list. Remember that the first item
(21) is sitting at position 0, so 23 is at index 2. Here is the code
below:
a = [21, 34, 23, 34, 56, 67, 68]
sliced = a[2:6]
print(sliced)
Output:
[23, 34, 56, 67]

2. Here is the code below. Strings have a replace() method that we can
use to replace items in a string. The replace() method accepts two
arguments. The first item is the substring we want to replace, and
the second item is the substring we are replacing it with.
a = "I hate my bike"
a = a.replace('hate','love')
print(a)
Output:
I love my bike

3. We use a loop and conditional statement to find duplicates.


list1 = [10, 20, 30, 30, 10, 40, 60, 70, 60]

duplicates = []
for number in list1:
if list1.count(number) > 1:
if number not in duplicates:
duplicates.append(number)
print(duplicates)
Output:
[10, 30, 60]

4. We use the Bitwise operator (|) to merge the two dictionaries.


a = {'name': 'John','age': 36}
b = {'course':'Python', 'duration': '6 months'}

merged = a | b
print(merged)
Output:
{'name': 'John', 'age': 36, 'course': 'Python', 'duration':
'6 months'}

174 | Page
Chapter 3
1. The modulus operator returns the remainder of a division operation.
To check if a number is even, we should divide the number by 2, and
it should return a remainder of zero. So we get a true output because
24 is fully divisible by 2, making it an even number.
a = 24
print(a % 2 == 0)
Output:
True

2. Here is the code below. We use the in operator to find the substring.
a = "One of the best students in our class is Mark"
print("Mark" in a )
Output:
True

3. The floor division (//) returns a whole number. It rounds off the
results of the division to the nearest whole number less than x. This
means that if the results of a division are 3.8, the floor operator will
return a 3. The division operator, on the other hand, returns a
floating number.
x = 8
y = 3
# using the division operator
b = x / y
print('The answer is ', b)

# using the floor division operator


b = x // y
print('The answer is ', b)
Output:
The answer is 2.6666666666666665
The answer is floor is 2

175 | Page
Chapter 4
1. We use the max() and min() functions for this challenge. Here is the
code below:

a = [10, 20, 30, 30, 10, 40, 60, 70, 60]


b = [12, 45, 67, 88, 45, 34, 21]
sum1 = max(a) + min(b)
print('The sum is', sum1)
Output:
The sum is 82

2. We can rewrite the code like this:

a = 3**4/2**4
print(a)
Output:
5.0625

Chapter 5
1. Here is the code below. Remember to use typecasting to convert
string inputs into integers.

a = int(input('Enter a number:'))
b = int(input ('Enter another number: '))
c = int(input('Enter the last number: '))

ans = (a * b)/c
print('The answer is ', ans)
Output:
The answer is 135.0

176 | Page
Chapter 6
1. In the following code, we use the sum() function and the len()
function. The sum function sums up the elements in the list. The
len() function returns the length of the list. Dividing the sum by the
length returns the average.

def list_average(lst:list):
avg = sum(lst)/len(lst)
return 'The average is', avg

print(list_average([1,2,4,6,7]))
Output:
('The average is', 4)

2. Here is the code below. We use the join() method.

def join_string(a):
a = '_'.join(a)
return a

print(join_string('love'))
Output:
l_o_v_e

Chapter 7
1. The filter() function uses the lambda function to filter the list for
numbers that are floats.

list1 = [23.6, 50, 43.5, 63, 78.8, 99, 75]

lst = list(filter(lambda x: type(x) == float, list1))


print(lst)
Output:
[23.6, 43.5, 78.8]

177 | Page
Chapter 8
1. Using list comprehension, we put all the code in one line. We use the
modulus operator (%) to find numbers in the list that return a
remainder when divided by 2.

list1 = [1, 2, 3, 5, 7, 9, 13, 17, 20]


# using list comprehension
odd_num = [i for i in list1 if i % 2 != 0]
print("Odd numbers in the list are", odd_num)
Output:
Odd numbers in the list are [1, 3, 5, 7, 9, 13, 17]

2. We use the loop to go over the string. The conditional statement will
find all the letters in the string that are uppercase. Once we find
them, we add them to the count variable.

str1 = "Mary Is Not in SchooL Today"

# Create a variable count


count = 0
for letter in str1:
# Increment the valuable
if letter.isupper():
count += 1
print(f'The number of uppercase letters is: {count}')
Output:
The number of uppercase letters is: 6

178 | Page
Chapter 9
1. Here is the code below:

months = ["June", "July", "August",


"September", "October"]
for month in months:
if month == 'August':
continue
print(month, end = ' ')
Output:
June July September October

2. Once the loop finds 6 in the sequence, the break statement will stop
the loop.
num_list =[3, 7, 11, 9, 2, 4, 6, 8, 10]

for num in num_list:


print(num)
if num == 6:
break
Output:
3 7 11 9 2 4 6

3. We are going to use the continue statement. The continue statement


tells the loop that once it finds the name "School", it should stop the
iteration, skip school, and start a new iteration.

dict1 = {"Name": "Mary",


"School": "Yale",
"age": 22}

for key in dict1.keys():


if key == 'School':
continue
print(key)
Output:
Name
age

179 | Page
Chapter 10
1. A for loop iterates over a sequence or iterable. A while loop iterates
over a block of code as long as a condition evaluates to true.

2. This code will run until there are 4 even numbers in the list. A while
loop will ensure that the code runs as long as there are less than 4
items in the list.

def even_num():
even1 = []
while True:
number = int(input('Enter a number:'))
if number % 2 == 0:
even1.append(number)
if len(even1) == 4:
break
return even1

print(even_num())

Chapter 11
1. We use try and except blocks to ensure that we handle the value
error. Here is the code below:

def your_vat():
try:
price = int(input("Enter the price of item: "))
vat = int(input('Enter vat:'))
except ValueError:
print("Enter a valid number")
else:
total_price = price + (price * vat / 100 + 1) - 1
return total_price

print(your_vat())

180 | Page
Chapter 12
1. We create a parent class called Cars. The other classes are inheriting
the attributes of the parent class. The Cars class is passed as a
parameter of the child classes.

class Cars:
def __init__(self, color, doors, transmission):
self.color = color
self.door = doors
self.transmission = transmission

# BMW is inheriting from the Cars class


class BMW(Cars):
def __init__(self, color, doors, transmission):
# This line ensures that BMW inherits from the Cars class
Cars.__init__(self, color, doors, transmission)

# Tesla is inheriting from the Cars class


class Tesla(Cars):
def __init__(self, color, doors, transmission, electric_car: bool):
# This line ensures that Tesla inherits from the Cars class
Cars.__init__(self, color, doors, transmission)
self.electric_car = electric_car

# Toyota is inheriting from the Cars class


class Toyota(Cars):
def __init__(self, color, doors, transmission):
# This line ensures that Toyota inherits from Cars
Cars.__init__(self, color, doors, transmission)

toyota = Toyota("red", 4, "Automatic")


tesla = Tesla("white", 4, "Automatic", electric_car=True)

181 | Page
Chapter 13
1. We are using the escape ("\n") to ensure that each name in the
list is written on a separate line.
names = ["John","Mary","John","Peter"]

with open('names.txt','w') as file:


for name in names:
file.write(name)
file.write("\n")

# Reading the file


with open('names.txt', 'r') as file:
print(file.read())
Output:
John
Mary
John
Peter

2. Here is the code below:


# Appending a name to file
with open('names.txt', 'a') as file:
print(file.write('\nSalah'))

# Reading file
with open('names.txt', 'r') as file:
print(file.read())
Output:
John
Mary
John
Peter
Salah

3. The os is an in-built module. We just have to import it.


import os
os.remove('cars.txt')

if os.path.exists("names.txt"):
os.remove('names.txt')
else:
print('No such file exists')

182 | Page
Chapter 14
1. Here is the code below:

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']

2. Pandas is not a built-in module. It must be installed on your


system before you can import it.

import pandas as pd

cars = {"BMW": "X6","Tesla": "X", "Honda": "Civic" }

df = pd.DataFrame(cars.items(),
columns=["Model","Brand"])

print(df)
Output:

183 | Page
Chapter 15
1. Remember to import the datetime module for this challenge.

from datetime import datetime

def your_age():
while True:
birth_year = input("Enter your birth year: ")
# Using datetime to get the current year
current_year = int(datetime.now().strftime("%Y"))
if len(birth_year) != 4:
print("Please enter a four-digit year")
elif int(birth_year) >= current_year:
print('Please enter a valid year')
else:
age = current_year - int(birth_year)
return f'You are {age} years old.'

print(your_age())

184 | Page
Part 2-Practice Questions

185 | Page
Syntax and Variables
1. Which of the following correctly defines a syntax in Python?
a. It’s a set of rules on how a Python code will be written and
interpreted
b. It’s a set of commands found in Python
c. It’s a set of in-built functions and classes in Python
programming
d. All the reserved words found in Python

2. Which one of the following correctly describes a variable?


a. A reserved memory location for an object
b. A number in Python
c. A string and number in Python
d. A string in Python

3. You cannot start a Python variable with an uppercase letter. True


or False
a. True
b. False

4. Mary writes the following code:


myname = "Mary"
From the above code, which one is a variable?
a. Mary
b. myname and “Mary
c. myname
d. None of the above

5. John is trying to create a variable name for a value called orange.


Which one of the following codes will return an error?
a. fruit = "Orange"
b. Fruit = "Orange"
c. _fruit = "orange"
d. -fruit- = "Orange"

186 | Page
6. In Python, indentation is merely for readability. It has no impact on
how the code is interpreted. True or False?
a. True
b. False

7. Look at the code below:


x = 2
print(x)
When this code is run it will generate an error. True or False?
a. True
b. False

8. Which one of the following is an improper name for a variable in


Python?
a. seven
b. numberSeven
c. Number-seven
d. number_Seven

9. Mike writes down the following code:


9Myname = "Mike"

Mike runs the code and it generates a syntax error. What is wrong
with the code?
a. The name Mike should not be in quotation marks
b. The name Mike should not start with a capital letter
c. The variable name should not start with a number
d. Myname should not be written as one word

187 | Page
10. Peter wants to create a string, so he writes the following code:
myname = Peter
print(myname)

Peter tries to run the code but it generates an error. What is wrong
with the code?
a. The variable name should start with a small letter
b. The name Peter should start with a small letter
c. The name Peter should have been put in quotation marks
d. All the above

11. Which of the following variable names are not allowed in Python?
Select all that apply.
a. My_name
b. my_name
c. My-name
d. _myname
e. My name

12. Which one of the following cannot be used as a variable name?


a. False
b. Name2
c. Cars
d. Car

13. John writes the following code:


list = 7
print(list)

Rose tells John that he cannot use "list" as a variable name. John
argues that he does not see any reason why he should not use it when
the code runs just fine. Explain to John why Rose is right to insist
that the variable name be changed.

188 | Page
14. Which one of the following is a reserved keyword in Python and
cannot be used as a variable name?
a. del
b. jail
c. may
d. lay
15. Jane wants to use the word "print" as a variable name. Can she
use this name in Python?
a. Yes, she can use it as a variable name as it is not a reserved
word in Python
b. print is a built-in function in Python so it should not be
used
c. She can use it because some Python reserved words can be
used as variable names in some instances
d. Yes, using the word will not generate an error
16. Kelly writes the following code:
fruit = "Mango"
print(Fruit)
The code generates an error "Fruit is not defined". What is wrong
with Kelly’s code?
a. Variable names are case-sensitive so fruit is not equal to
Fruit
b. Mango should not be put in quotation marks
c. There is no variable called fruit
d. All the above.
17. Beyonce writes the following code:
Fruit = "Mango"
Which of the following is not equal to the code above? Select all
that apply.
a. Fruit =str('Mango')
b. Fruit = "Mango"
c. fruit = Mango
d. Fruit =int(Mango)

189 | Page
18. John writes the following code:
a, b, c = "alphabet", "banana", "car"

Which one of the following codes will print "car"?


a. print(a)
b. print(b)
c. print(c)
d. print(:2)

19. Which one of the following will be interpreted as a comment in


Python?
a. //This is a comment//
b. #This is a comment
c. \\This is a comment\\
d. **This is a comment**

20. John wants to write a code with a variable name car and its value
should be Toyota. Which of the following will not generate an
error? Select all that apply.
a. car = "Toyota"
b. car = 'Toyota'
c. car = Toyota
d. Car = Toyota

21. What is the difference between a statement and an expression in


Python?
a. A statement is a line of code that does something, while an
expression is a line of code that evaluates into something
b. An expression is a line of code that does something, while a
statement is a line of code that evaluates into something
c. A statement is a line of code that combines something, while
an expression is a line of code that divides something
d. A statement is a line of code that runs all the time, while an
expression is a line of code that runs when called

190 | Page
22. Which one of the following is an expression?
a. while loop
b. print(name)
c. 'firstname' + 'lastname'
d. if statement

Data Types and Typecasting


23. Which of the following is a data type in Python? Select all that
apply.
a. variable
b. float
c. integer
d. complex

24. Which one of the following data types is an integer?


a. 20
b. 21.2
c. 21.22
d. 0.1

25. Mary writes the following code:


y = 1.5
print(type(y))
What data type do you get when you run this code?
a. float
b. int
c. tuple
d. list

191 | Page
26. John writes the following code:
name = "John"
print(type(name))

What data type do you get when you run this code?
a. str
b. float
c. set
d. tuple
27.
fruits = ["apples", "mangoes", "Oranges"]
print(type(fruits))

What data type do you get when you run this code?
a. dict
b. tuple
c. list
d. bool
28.
apples = {"apples", "mangoes", "Oranges"}
print(type(apples))

What data type do you get when you run this code?
a. list
b. dict
c. set
d. tuple

29. What data type do you get when you run the code below?
fruits = ("mango", "orange", "lemon")
print(type(fruits))

a. dict
b. mango
c. tuple
d. list

192 | Page
30.
cars = ["BMW", "Mazda", "Honda", False, 1,2,9,10]
print(type(cars))

What data type do you get when you run this code?
a. tuple
b. list
c. float
d. dict

31. Sam writes the following code:


y = False
print(type(y))

What data type do you get when you run this code?
a. Set
b. bool
c. dict
d. float

32. Michael writes the following code:


y = {"name": "Peter", "school": "yale"}
print(type(y))

What data type do you get when you run this code?
a. dict
b. tuple
c. list
d. let

33. Which one of the following best explains typecasting?


a. Converting one data type into another using a Python
function
b. Typecasting is printing out Python data
c. Converting numerical type data into a string
d. Writing clean code in Python

193 | Page
34. Mary wants to apply typecasting to convert variable x, so she
writes the following code:
x = 5
x = float(5)
print(x)

What is the output of the code?


a. 5.0
b. 5
c. 5.1
d. 4

35. Using typecasting, write a code that converts the following code
into an integer.
x = "10"

Print out the data type of your new variable.

36. Using typecasting convert the following code into a string.


x = 10

Print out the data type of your new variable.

37. Convert the following code into a float using typecasting. Print out
the data type of your new variable.
x = 23

38. John wants to convert a variable y which is an integer into a


string. How does he convert an int variable into a string using
typecasting?
a. y = string(y)
b. y = str(y)
c. y =float(y)
d. y = int(y)

194 | Page
39. In Python, casting is the process of converting a variable into
another type. What is the output of the following code?
y = 4.67
y = int(4.67)
print(y)
a. 5
b. 4
c. 4.7
d. 5.7

Python Tuples
40. Alison wants to create a tuple with one element. Is it possible to
create a tuple with one element in Python? If it is possible, create
one.

41. Create a tuple with three items – Jane, Mary, and Alice. Use the
variable "names" for this tuple. Use the type() function to check
the data type of your variable.
42. Write a code to print the name "Alice" from your tuple (question
41).

43. Write a code to check the length of the tuple (question 41). Print
out the length.

44. Your boss, Jerry, has asked you to add another item to your tuple
(question 41). Write a code to add "Maria" to the tuple.

45. Your boss, Jerry, has come back and now wants the name Maria
(question 41) removed from the tuple. Write a code to remove the
name Maria from the tuple.

46. Your boss suspects that the name Jane appears more than once in
the tuple of names. Use the tuple method count() to check how
many times the name Jane appears in your tuple (question 41).

195 | Page
47. Which one of the following is a tuple method?
a. cut()
b. append()
c. index()
d. sort()

48. Which one of the following is true about tuples?


a. No duplicates are allowed in a tuple
b. You cannot create a tuple of Boolean data types
c. You cannot have a tuple with different data types
d. There is no limit to the number of items you can add to a
tuple

49. There are two ways to create a tuple; using round brackets () and
using a tuple constructor. Create a tuple of colors – Red, Blue,
and Green, using a tuple constructor. Print the tuple of colors.

50. What is the difference between a tuple and a set? Select all that
apply.
a. Tuples have ordered values while sets don’t
b. Sets have ordered values while tuples don’t
c. Sets are mutable while tuples are immutable
d. Tuples are immutable while sets are mutable

51. Mary has written down the following codes:


x = (1, 2, 4, 6, 7, "John")
y = {2, 1, 4, 6, 6, 7}
Which one is a set and which one is a tuple?
a. x is a tuple, y is a set
b. y is a tuple, x is a set
c. x is a tuple, y is a tuple
d. x is a set, y is a set

196 | Page
52. You can use the sort() method to sort a tuple in ascending order
only. True or False?
a. True
b. False

53. Can you have duplicate items in a tuple?


a. No, you cannot have duplicates in a tuple
b. Yes, you can have duplicates in a tuple

54. John wants to know the length of the tuple below:


animals = ("dog", "cat", "duck", "chicken")
Which one of the following codes will give the length of the
tuple?
a. print(len(animals))
b. print(len.animals)
c. print(len(animals)
d. print(animals.len)

55. John wants to change the last item in the tuple (question 54). He
wants to replace "chicken" with "cow". Which one of the following is
the right code to update the tuple?
a. animals[3] = "cow"
b. animals[2] = "cow"
c. animals[:3] = "cow"
d. Tuples are immutable

56. Which one of the following codes will delete "dog" from a tuple
(question 54)?
a. animals. delete["dog"]
b. animals. delete("dog")
c. Impossible to delete an item in a tuple
d. animals.delete[dog]

197 | Page
57. Jane has written down the following code:
animals = ("dog", "cat", "duck", "chicken")
fruits = ("oranges", "apples", "mangoes", "bananas")

Write a code to combine the two tuples.

58. Jane wants to double the code elements in the following tuple:
cars = ("BMW", "Isuzu", "Nissan")

Write a code to double each element in the tuple.

59. Which one of the following is a tuple method?


a. add()
b. append()
c. count()
d. delete()

Lists in Python
60. This data structure is mutable; its values can be stored between
square brackets; and it can store different types of data. Which
data structure is this?
a. tuple
b. dict
c. list
d. Boolean

61. Create a list of numbers 0 – 10. Give your list variable name -
numbers. Print out the class/data type of your list.

62. Ashanti writes down the following code:


numbers = [10, 20, 40, 70, 60, 90, 100, 55, 78, 89]

Write a code to print out numbers 70 - 60 from your list.

198 | Page
63. Write another code to print out numbers 70 – 100 from the list
(question 62).

64. Your boss has asked you to sort your list (question 62) in
ascending order. Using the sort() method, write a program to
sort your list. Print out the sorted list.

65. A sort() method sorts a list only in ascending order. True or


False?
a. True
b. False

66. Which one of the following is not a list method?


a. sort()
b. copy()
c. return()
d. pop()

67. Jimmy writes the following code:


cars = ["Volvo", "Honda", "BMW",
"Toyota", "Toyota"]

print(cars.count("Toyota"))

What is the outcome of running this code?


a. 1
b. 2
c. 3
d. 4

199 | Page
68. Mark has written down the following code:
cars = ["BMW", "Honda", "Nissan", "Toyota"]

Mark wants to print "Toyota" on the list. What code should Mark
write?
a. print(cars[3:])
b. print(cars[4:])
c. print (cars[3:1])
d. print(cars[3])

69. Which one of the following is not a property of a list in Python?


a. It can hold duplicate items
b. It can be changed
c. It is immutable
d. It is ordered

70. Janet writes down the following code:


a = [1, 2, 4, 4, 5, 6, 7, 8, 9]

Janet wants to remove 4, 4, and 5 from the list. Help Janet with a
code that will remove these numbers. Print out the updated list.

71. Kate writes the following code:


a = [1, 2, 2, 3, 3, 4, 5, 6, 9, 8]
Which of the codes below will return the length of the variable a?
a. print(len(a))
b. print(len(a)
c. print(a.len)
d. print(len.a))
72. Which one of the following is not a list method?
a. pop()
b. drop()
c. remove()
d. sort()

200 | Page
73. Pat writes the following code:
girls_names = list(("Mary", "Rose", "Kate", "Amanda"))

Pat wants to remove the name "Amanda" from the list. Which one
of the following codes will remove the name?
a. girls_names.remove()
b. girls_names.pop()
c. girls_names.sort()
d. girls_names.drop()
74. Which one of the following methods will add an item to the end
of the list?
a. add()
b. append()
c. join()
d. insert()
75. What is the difference between append and extend methods?
a. extend adds a single item to the list, while append
increases the list by the number of iterable items
b. append adds a single item to the list, while extend increase
the list by the number of items in an iterable
c. There is no difference between the two
d. append is a string method while extend is a list method
76. Simon writes the following code:
cars = ["Volvo", "Honda", "BMW", "Toyota"]

Simon writes another code to replace some items in the list


below.
cars[2:4] = ["Audi","Ford"]

Which cars from the original list will be replaced?


a. Volvo and Honda
b. BMW and Toyota
c. Honda and Toyota
d. Volvo and Toyota

201 | Page
77. Below is a list of cars.
cars = ["Volvo", "Honda", "BMW", "Toyota"]

Which one of the following codes will replace Volvo with Benz?
a. cars[-1]= "Benz"
b. cars[1]= "Benz"
c. cars[2]= "Benz"
d. cars[-4]= "Benz"

78. Mary writes the following code:


cars = ["Volvo", "Honda", "BMW", "Toyota"]
print(cars.index("Volvo"))

What is the outcome of running this code?


a. 0
b. 1
c. 2
d. 3

79. Which one of the following is not a list method?


a. sort()
b. sorted()

80. Steve writes the following code:


x = [1, 3, 5, 7, 8, 9, 2, 4, 5, 7, 10]

Write a code to sort the list in ascending order using the sorted()
function. Create a new variable for the sorted list.

202 | Page
Python Sets
81. Which of the following is true about sets? Select all that apply.
a. Sets are surrounded by square brackets
b. Sets are ordered
c. You can change sets after they are created
d. Sets are surrounded by curly brackets
82. Create a set called "car". The set should have 3 items; Benz,
Ford, and Toyota. Print out the car class type.

83. Mary is asking that you change your set (question 82). She wants
you to replace Toyota with Honda. Write a code to replace the
cars. Print out the code.
84. Peter writes the following code:
set1 = {10, 67, 90, 91, 77, 73}
set2 = {2, 1, 4, 6, 8, 7}

Peter wants to merge set2 elements into set1 to create one set.
Write a code to merge the sets. Print out set1 after the merge.
(Hint: there is a set method you can use for this.)

85. Write a code to remove the number 77 from the merged set you
created (question 84). Use the set method. Print out the updated
set.
86. Which one of the following is not a set method?
a. remove()
b. method()
c. pop()
d. union()

87. Write a code to clear all the elements of the following set. Print
out the results.
v = {12, 90, 89, 23, 56}

203 | Page
88. Using the set() constructor, create a set of numbers ranging from
1 to 10. The variable name of the set should be num_set. Print
out the class type of the variable.

89. Write a code using len() to determine the length of your set
(question 88).

90. You can add new items to a set. True or False?


a. True
b. False

91. What is the difference between the update() method and the
union() method?

92. Which of the following is true?


a. Sets can have duplicates
b. Sets are ordered
c. Sets have a similar bracket type to dictionaries
d. You cannot put a set inside a set.

93. Write a code to add items from cars2 to cars below. Print out
the combined set.
cars = {"Volvo", "Honda", "BMW", "Toyota"}
cars2 = {"Audi","Ford"}

Operators in Python
94. Which one of the following operators is used to add values
together?
a. *
b. +
c. –
d. %

204 | Page
95. The * operator is used for multiplication.
x = 2**3
print(x)
What answer do we get when we run the code?
a. 6
b. 8
c. 12
d. 16

96. John writes the following code:


y = 6 * 3
print(y*2)
What is the result of this expression?
a. 11
b. 12
c. 36
d. 40

97. Which one of the following is a division operator in Python?


a. //
b. /
c. %
d. \\

98. Kelly writes the following code:


x = 6//4
print(x*2)
What is the result of this code?
a. 6
b. 3
c. 4
d. 2

205 | Page
99. What is the result of running this code.
x = 6/4
print(x*2)

What do you get when you run this code?


a. 1.5
b. 2.0
c. 3.0
d. 4.0

100. What is the difference between the floor division operator


operator (//) and the division ( /) operator?
a. // operator return the result with decimal places, while /
operator does not return decimal places
b. //operator returns the result without decimal places, while
/ operator returns the results with decimal places
c. // is a division operator while / is a modulus operator
d. There is no difference between the two operators

101. Which one of the following is the same as c = c + 5?


a. c =+ 5
b. c += 5
c. c - = 5
d. c = - 5

206 | Page
102. John has written down the following code:
b = 12%3
print(b)

What is the result of running this code?


a. 4
b. 0
c. 3
d. 12

103. Which one of the following is not a logical operator in Python?


a. and
b. or
c. not
d. equal

104. Tina writes and runs the following code:


a = 10 != 5
print(a)
What is the result of this code?
a. True
b. False
c. 5
d. It generates an error

105. What is the shorthand for y = y // 5?


a. y = y/5
b. y /=5
c. y //=5
d. y =//

207 | Page
Strings and Boolean Values
106. What is a string in Python?
a. A sequence of words not surrounded by quotation marks
b. A sequence of characters surrounded by quotation marks
c. A sequence of numbers
d. A sequence of numbers surrounded by square brackets
107. The strip() method and split() method do the same thing to
a string. True or False?
a. True
b. False
108. Which one of the following variables will not return a class
type of string?
a. y = str(5)
b. y = '5'
c. y = "5"
d. y = 5
109. Mary writes the following code:
y = "I am learning python"
Which one of the following codes will slice the word "learning"
from variable y?
a. print(y[:5])
b. print(y[6: 13])
c. print(y[5:13])
d. print(y[5:]
110.
y = "I am learning Python"
Which one of the following codes will slice the word "Python"
from the variable y?
a. print(y[-6:])
b. print(y[-5:])
c. print(y[-5:9])
d. print(y[-6:-9])

208 | Page
111.
y = "I am learning Python"
Write a code to replace "learning" with "studying" in the variable y.

112. Mark writes the following code:


fruits = "#mangoes, oranges#"
Write a code that removes the # characters from the code.

113. Dwayne writes the following code:


y = "I don’t like "lazy" people"
print(y)
Dwayne runs the code, but it returns an error. What is wrong with
the code?
a. He cannot use opening and closing quotes
b. He cannot use double quotes inside a string surrounded by
double quotes
c. He cannot use capital letters inside the string
d. All the above.

114. Which of the following string methods will capitalize the first
character of a string?
a. capitalize()
b. upper()
c. casefold()
d. capital()

115. Which one of the following string methods converts a string


into lowercase letters?
a. lower()
b. small()
c. casefold()
d. all the above

209 | Page
116. Which one of the following string methods converts the whole
string into uppercase letters?
a. upper()
b. capitalize()
c. casefold()
d. capital()

117. Derick is trying to figure out the length of a string. Which one
of the following methods will give him what he is looking for?
a. values()
b. len()
c. size()
d. number()

118. Which one of the following escape characters tells Python to


start a new line?
a. \\
b. \b
c. \n
d. n\
119. Karen writes the following code:
a = bool(a)
print(a)
What value will this code return?
a. Zero
b. True
c. False
d. Empty

120. What will the following code return when you run it?
a = 7 > 7-1
print(a)
a. True
b. False
c. Error
d. Nothing

210 | Page
121. Janet writes the following code:
home = "The place where I relax"
print(isinstance(home, str))

What will this code return?


a. False
b. True
c. Str
d. Int

Python Dictionary
122. Which one of the following is a dictionary?
a. student = {"name": "John", "age": 23}
a. student = ("name": "John", "age": 23)
b. student = ["name": "John", "age": 23
b. student =dict[name: John, age: 23]

123. Which one of the following is not a property of a dictionary?


a. Immutable
b. Ordered
c. No duplicate keys
d. None of the above

124. John wants to access the value of the following dictionary:


cars = {"name": "Ford", "year": 1992}

Which one of the following codes will print out the values: Ford
and 1992?
a. print(cars.values())
b. print(cars.keys())
c. print[(cars.values())]
d. print (Ford.1992)

125. Write a code to access the keys and values of the car's dictionary
(question 124). Use a for loop.

211 | Page
126. John is trying to change the name of the car name (question 124)
to BMW. Write a code that will change the value of the dictionary.
a. cars["name"]= "BMW"
b. cars["values"] = "BMW"
c. cars("name") = "BMW"
d. cars[values] = BMW

127. Help John with a code that will change the key from "name" to
"brand" (question 124).
a. Cars["values"] = "brand"
b. cars ["keys"]= "brand"
c. cars ["name"] = brand
d. Keys cannot be changed

128. Write a code to add a key named "color" and its value of "white"
to the dictionary (question 124).

129. Write a code to change the value from 1992 to 2004 in the
dictionary (question 124).

130. Which one of the following is a dictionary method?


a. add()
b. update()
c. count()
d. append()

131. Alison writes the following code:


cars = {"names": "Nissan", "year": 2007}

Alison wants to remove the key "year" from the dictionary. Write
a code to remove the key from the dictionary.

132. Alison changes her mind and decides to delete the dictionary.
Write a code that will delete the dictionary (question 131).

212 | Page
133. Mary writes 3 dictionaries:
student1 = {"name": "John", "grade": "F"}
student2 = {"name": "Alison", "grade": "B"}
student3 = {"name": "Ben", "grade": "C"}
Write a code that will combine these dictionaries into one nested
dictionary. Call the dictionary, students.
134. Mary decides to remove student3 from the nested dictionary.
Help her with a code that will remove the student3 from the
nested dictionary (question 133).

135. Which one of the following methods removes all the elements
from a dict?
a. remove()
b. pop()
c. popitem()
d. clear()

136. Here is a dictionary:


mydict = {"name": "Mary", "occupation": "Singer"}

Write a code to create a copy of this dict.


a. newdict = mydict.copy
b. newdict = mydict.copy()
c. newdict = mydict.copy[]
d. newdict = copy(mydict)
137. Using the get() method, write a code to access the dictionary
value ("singer") (question 136).

138. Which one of the following is not a dictionary method?


a. popitem()
b. delete()
c. pop()
d. setdefault()

213 | Page
139. Which one of the following is true about dictionaries?
a. Dictionaries allow duplicate keys
b. Dictionaries allow duplicate values
c. Dictionaries do not allow duplicate values and keys
d. Dictionaries allow duplicate keys and values

140. What is the main difference between a dict and a list?


a. Items in a list are accessed by keys, while items in a dict
are accessed by values
b. Items in a dict are accessed by keys while items in a list are
accessed by referencing their position
c. Items in a list are not ordered while items in a dict are
ordered
d. None of the above
141. Jane writes the following code:
x = {"name": "carol", "age": 23, "school": "Yale"}
Write a code to access the school Yale from the dictionary.

142. Which of the following is a true similarity between a dictionary


and a list?
a. They are both immutable
b. They are both mutable
c. They are both sequential
d. They are both surrounded by square brackets

143. What is the difference between a dictionary and a tuple?


a. Dictionary is mutable while a tuple is immutable
b. Dictionary is immutable while a tuple is mutable
c. Dictionary is ordered, while a tuple is not ordered
d. There is no difference between a dictionary and a tuple

214 | Page
144. Write a for loop to print all the values in the following
dictionary.
x = {"name": "carol", "age": 23, "school": "Yale"}

145. Write a code to loop through all the keys in the dictionary
(question 144).

146. Write a code to check if the key "name" is in the dictionary x. If


the key is in the dictionary, let the code print "name is one of
the keys." If it is not in the dictionary, the code should say
"name is not one of the keys" (question 144).

147. John writes the following code:


a = {'name': 'John', 'age': 25}
b = {'school': 'Yale', 'location': 'USA'}

Write a code to combine these two dictionaries using a bitwise


OR operator (|).

Functions in Python
148. Which one of the following correctly defines a function?
a. A block of code that performs a specific task and runs all the
time
b. A block of code that performs a specific task and runs when
called
c. A block of code that loops a function
d. A block of code that runs non-stop and only stop when a
break is called
149. Which one of the following is a keyword for creating a function?
a. function
b. def
c. fun
d. dif

215 | Page
150. Which one of the following is a valid way of creating a function?
a. def my_car:
b. def my_car():
c. def my car:
d. def_my_car():

151. What are "arguments" in a function?


a. Values that are passed into a function when it is called
b. Information that is left out of a function
c. The name of the function
d. None of the above

152. John wants to create a function named "car" with a parameter


called "carname." Which one of the following is a valid way to
write the function?
a. def_car (carname):
b. def car (carname):
c. def car ("carname"):
d. Def car("carname"):

153. Create a function called add that takes two parameters, number1
and number2. Return the sum of the two numbers.

154. John wants to create a function called my_function that will


have one parameter, car, and a default argument, BMW. Which
one of the following correctly creates the function?
a. def my_function (car_BMW):
b. def my_function ("car_BMW"):
c. def my_function (car = "BMW"):
d. def_myfunction (car =BMW):

155. What is the purpose of the return statement in a function?


a. To tell the function to return the results of the function
b. To replace print
c. To print the function results
d. To delete the function results

216 | Page
156. Which of the following is an advantage of a function? Select all
that apply.
a. With functions, you don’t have to repeat code
b. It makes the code clean, making it more readable
c. Large code is broken down into functions for easy tracking
d. All the above

157. Write a function called multiply_divide with three parameters,


a, b, and c. The function multiplies the two parameters, a and b,
and divides them by c. Create a local variable for the function
(variable name = results). Pass 12, 24, 8, as arguments to the
function. Your function should return 36.0. Print the results.

158. Which one of the following is true?


a. A function cannot accept zero parameters
b. A function name can also include reserved Python
keywords
c. A function can accept zero parameters
d. A function does not accept a local variable

159. Mary told John to create a single function, as it is possible to use


different arguments with a function every time it is called. Is Mary
right that we can use different arguments with a function every
time it is called?
a. She’s not right, we cannot use different arguments for one
function
b. She’s right, we can use different arguments for one
function
c. We can use different variables but not different inputs
d. A function does accept different types of inputs.

217 | Page
160. Debra wants to write a function, but she is not sure how many
arguments the function should have. How can she properly write
this function?
a. Pass ## as the argument of the function
b. Pass *args as the parameter of the function
c. Write a function without arguments
d. She must know the actual number of arguments before
writing the function

161. Is there a limit to the number of parameters that a function


can take?
a. A function cannot take over 10 parameters
b. A function cannot take over 5 parameters
c. A function cannot take over 2 parameters
d. There is no limit to the number of parameters a function can
take
162. Debra creates the following function:
def subtract(num1,num2):
sub1 = num1 - num2
return sub1
print(subtract(24,26))

What is wrong with this function?


a. The sub1 variable should have started with a capital letter
b. The sub1 and return statement should have been indented
c. The print statement should have been outside the function
d. The function is missing the return call

163. How do you use a variable that is inside a function outside of a


function?
a. You cannot use a variable outside a function in a function
b. Declare the variable, a global variable
c. Change the name of the variable outside the function to
global
d. Use a keyword in the name of the function

218 | Page
164. Jane writes the following function:
def my_fun()
sum1 = 11 + 11
return sum1
print(my_fun())

This function generates an error. What is wrong with this function?


a. There is nothing wrong with the function
b. After my_func(), there is no colon (:)
c. The function should not be indented
d. sum is a reserved word in a function

165. What is a local variable when it comes to functions?


a. A variable outside a function
b. A variable declared inside a function
c. A variable imported into the function
d. None of the above

166. Karen writes the following code:


def subtract(num1, num2):
sub1 = num1 - num2
return sub1

Karen wants to call the function. If the arguments for num1 and
num2 are 10 and 5, respectively, which of the following will call
and print the function?
a. print(10,5)
b. print(10 - 5)
c. print(subtract(10,5))
d. subtract(10,5))

219 | Page
167. Ken has created the following function:
def my_function():
Ken does not know yet what to add to the function. He wants to
keep the function empty. When he runs the function, he gets an
error. What should he add to the function to avoid the error?
a. Add the keyword pass to the function
b. Add the keyword return to the function
c. Add the keyword global to the function
d. Add the word the keyword del to the function

168. Write a function called convert that takes one argument, a


number in kilometers, and converts it to miles. Use the function
to convert 109km to miles and print out the answer. Round the
answer up to zero decimal points.

169. Write a function called rectangle_area, which takes two


parameters, a and b, calculates the area of a rectangle, and
multiplies it by 2. Return the answer and print it out (a = 15, b =
67).

170. Write a function that calculates the area of a triangle. The


function takes two parameters: base and height. Name the
function area_of_triangle. Pass 24 (base) and 67 (height) as
function arguments.

Conditional Statements
171. Create a function called max_num with one parameter, an
integer. If the number is less than 10, it should return "The
number is less than 10". Otherwise, it should return "The number
is not less than 10". Pass the number 12 as an argument for the
function.

220 | Page
172. Mika writes the following code:
a = 11
b = 10
if a != b:
print("it’s not equal")

The code generates an error. What is wrong with the code?


a. The if statement should be in a function
b. The print statement is not indented
c. "it’s not equal" should not be in inverted commas
d. The print statement should not be in round brackets

173. Which one of the following comes after the if statement in a code
with more than one conditional statement?
a. else statement
b. elif statement
c. or statement
d. and statement

174. Write a code (conditional statement) that compares two


variables, a and b. Variable a = 10, and variable b = 20. If a is
greater than b, it should return "a is greater than b". If b is greater
than a, return "b is greater than a". If the two numbers are equal,
return "The two numbers are equal."(a = 10, b = 20).

175. Mikel writes the following code:


a = 22
b = 34
Write an if statement that prints out, "B is superior to A" if b is
greater than a. Otherwise, print out "A is superior to B" if a is
greater than b.

221 | Page
176. Which one of the following reserved keywords is used in
conditional statements?
a. and
b. more
c. greater
d. than

177. Write the following code:


If a is greater than b and c is greater than b, print out "Life is not
fair", otherwise print "Life is beautiful." (a = 12, b = 15, c = 18).

178. Write the following code:


If a is greater than b or b is greater than c, print "Life is good".
Otherwise, print "Life is great."(a = 22, b = 34, c = 56).

179. Write the following in code. Put everything in one line (shorthand
syntax). If a is greater than b or a is greater than c, print out "Life
is good."

180. Which one of the following is a reserved keyword used in


conditional statements?
a. less than
b. or
c. more
d. less

222 | Page
For Loops
181. Which of the following statement best explains a for loop?
a. A loop that iterates over a function
b. A loop that iterates over an if statement
c. A loop that iterates over a given sequence of items
d. A loop that iterates over a string

182. William writes the following code:


a = "string"
Write a for loop that iterates through the variable a and prints
out all the letters.
183. Peter writes the following code:
animals = ("dog", "cat", "duck", "chicken")
Write a for loop that iterates through the tuple and prints out all
the items.
184. Which one of the following is used to stop the iteration of a for
loop?
a. halt
b. return
c. break
d. cancel

185. Ken writes the following code:


cars = ["Volvo", "Honda", "BMW",
"Toyota","Toyota"]
Using a for loop and an if statement, write a program that iterates
through the list. The code should break after it prints "Honda".
186. Which one of the following is a reserved keyword used in a for
loop to stop and start a new iteration?
a. break
b. continue
c. proceed
d. next

223 | Page
187. Which of the following best explains the continue statement in a
for loop?
a. To cancel the iteration
b. To stop the current iteration and begin a new one
c. It has no impact on the iteration
d. It breaks the iteration

188. Mary writes the following code:


cars = ["Volvo", "Honda", "BMW",
"Toyota", "Toyota"]

Mary wants to iterate through the code, but she wants to skip
"BMW". Using a for loop and an if statement, write a code that
will print everything in the list except BMW.

189. What is the result of running the following code?


for x in range (10):
if x == 5:
break
print(x)

a. 1,2,3,4
b. 0,1,2,3,4,5
c. 0,1,2,3,4,5,6,7,8,9
d. 0,1,2,3,4

190. What is the result of running the following code?


for x in range(10):
if x == 5:
continue
print(x)

a. 1,2,3,4,5,6,7,8,9,10
b. 0,1,2,3,4,5,6,7,8,9,10
c. 0,1,2,3,4,6,7,8,9,10
d. 0,1,2,3,4,6,7,8,9

224 | Page
191. Ezil writes the following code for his project.
students ={"Student1": "Mary", "student2":
"John","student3":"Peter"}
for x in students.values():
print(x)

What is the result of the above code?


a. Mary, John, Peter
b. Student1, student2
c. John, Peter
d. Student1, student3, student3

192. John writes the following code:


x = "hello"
for letter in x:
if letter== "e":
continue
print(letter)

What is the result of running the code?


a. hello
b. hllo
c. ello
d. llo

193. What is the result of running the following code?


colors = ["Red", "Green", "Blue"]

for x in colors:
if x == "Blue":
break
print(x)
a. Green
b. Green, blue
c. Red, Green
d. Red, Green, Blue

225 | Page
194. Which of the following is the result of running this code?
colors = ["red", "green", "blue"]

for x in colors:
print(x)
if x == "green":
break

a. red, blue
b. red, green
c. green
d. red, green, blue

195. Which of the following is the result of running the code below?
colors = ["red", "green", "blue"]

for x in colors:
print(x)
if x == "green":
continue

a. red, green, blue


b. green, blue
c. red, green
d. red, blue, green

196. Mary writes the following code:


for x in range (2, 16, 8):
print(x)

What is the result of running the code?


a. 2, 3,4,5,6,7,8,9,10,11,12,13,14,15
b. 2,4,6,8
c. 2,3,4,5,6,7
d. 2,10

226 | Page
197. What is the result of running this code?
for x in range(2, 16, 4):
print(x)

a. 2,6,10,14
b. 2,8,10,14
c. 4,8,10,14
d. 2,16,4

198. What is a nested for loop?


a. A big loop
b. A loop within another loop
c. A small loop
d. None of the above

199. John writes the following codes:


a = [1,2,3]
b = [ "yellow", "green", "red"]
Write a code that loop over the two lists at the same time.

200.Which one of the following is false?


a. You cannot use a for loop in a function
b. You can use a for loop inside and outside a function
c. A for loop can be used to iterate through a set
d. All the above.

227 | Page
While Loops
201. What is the difference between a while loop and a for loop?
a. A for loop iterates over an iterable of known length, while
a while loop iterates over an iterable object as long as the
condition is True
b. A while loop iterates over an iterable of known length,
while a for loop iterates over an iterable object as long as
the condition is true
c. A for loop can be stopped while a while loop will iterate
forever
d. There is no difference between the two

202. Lex writes the following code:


a = 1
while a < 10:
print("This number is less than 10")

Maria warns Lex that if he runs this code, the code will run forever.
Is Maria right?
a. No
b. Yes

203. Write a while loop that prints out "This number is less than
10" five (5) times while the variable a is less than 10 (assume a =
1). Remember to increment the variable a by 2 for every iteration.

204. How can you stop a while loop? Select all that apply.
a. The while loop will stop when a condition is false
b. You can stop the while loop by using the break statement
c. You cannot stop a while loop
d. A while loop will stop when the computer runs out of
memory

228 | Page
205. Ben writes the following loop:
a = -1
while a < 5:
a += 1
if a == 3:
continue
print(a)

Which of the following is the output of this code?


a. 1,2,3,4,5,6
b. 0,1,2,3,4,5
c. 0,1,2,4,5,
d. 0,1,2,3,4,5,6,7

206. What is the output of the following code?


a = -1

while a < 5:
a += 1
if a == 3:
break
print(a)
a. -1, 2,3
b. 0,1
c. -1, 2,3
d. 0,1,2

207. Write a while loop that prints out "This number is less than 5"
while variable a is less than 5. If a is no longer less than 5, it
should print "End of the loop." (Assume a = 1).

208. John wants to use a while loop to iterate through the dictionary.
Peter says he can’t use a while loop to iterate through a
dictionary. Is Peter right?
a. John is right, you can use a while loop to iterate through
the dictionary
b. Peter is right, you cannot use a while loop to iterate
through the dictionary

229 | Page
209. Can you use a for loop inside of a while loop?

210. Which one of the following is true?


a. If statements can only be used with while loops and not for
loops
b. If statements can be used with while loops and for loops
c. If statements can only be used with for loops and not with
while loops
d. All the above is not true

Python Math
211. Janet writes the following codes:
a = 23
b = 45
Write a function called add that adds these two variables and
returns the sum.

212. Write a function called multiply that multiplies the variables


(question 211) and return the answer.

213. Kevin writes the following codes:


a = 45
b = 66
c = 12
Write a function called multiply_and_divide that multiplies a
by b and divides that by c. Print out the answer.
214. Jane writes the following code:
x = (10,20,21,23,24,56,78,89)

Write a code that finds the minimum of x. Create a variable for


the minimum of x. Print out the answer.
215. Using a for loop and an if statement, write a code that finds the
max of x (question 214). Print out the answer.

230 | Page
216. Which one of the following is not a math method?
a. math.floor()
b. math.fabs()
c. math.divide()
d. math.comb()

217. Write a function that finds the square root of the variable below.
Print out the answer.
x = 64 (Use a math method)
218. Jane wants to know whether a given variable is a NaN (not a
number). Which one of the following should she use?
a. math.isinf()
b. math.isnan()
c. math.isqrt()
d. math.gcd()

219. John wants to write a code that will return an absolute positive
number from the following code:
a = -5.91

Write a code that will return the absolute value of variable a


variable using a math method.

220. What is the result of the following code?


z = math.floor(23.3)
print(z)
a. 22
b. 23
c. 21
d. 20

231 | Page
221. What is the result of the following code?
a = math.ceil(23.4)
print(a)

a. 24
b. 23
c. 22
d. 21
222. What is the result of the following code?
p = max (12,13,16)
s = 23
print(p*s)
a. 368
b. 276
c. 299
d. 943

223. John writes the following code:


c = 16 % 8
print(c)
What is the output of this code?
a. 2
b. 0
c. 8
d. 4

224. Mary writes the following code:


a = 2 * 2* 2 * 2* 2

Jane suggests that for a cleaner code, Mary should use


exponentiation. Rewrite the code using exponentiation.

225. Write a code that finds a remainder when you divide a by b.


Print out the results.
a = 89
b=9

232 | Page
226. Mary writes the following code:
a = 5 * 5 * 5 * 5

Mark suggests that Mary use the math method pow() for a
cleaner code. Use pow() method to rewrite this code? Print the
result.

227. What is the result of the following code?


a = math.trunc(18.9)
print(a)
a. 12
b. 13
c. 18
d. 19
228. What is the result of the following code?
x = pow(5, 3, 8)
print(x)

a. 240
b. 9.6
c. 3.75
d. 5

229. Which of the following is the output of the following code?


x = math.pi
y = 2*x
print(y)

a. 6.283
b. 3.141
c. 4.141
d. 2.223

233 | Page
230. Jane writes the following code:
x = min(12, 23,45,78, 90)
y = max(12,90,89,23,56)
v = (x,y)
z = math.prod(v)
print(z)

a. 455
b. 45
c. 121
d. 1080

User Input
231. Which one of the following functions is used to get input from
the user?
a. request()
b. input()
c. enter()
d. include()
232. Write a code that asks a user to input their name. The variable
name in the code should be my_name.

233. Write a function called adds that sums two variables, a and b.
The code should request the user to input a and b. Remember to
convert the user input into an integer using typecasting. Print out
the answer. The user inputs you should enter once prompted by
the code should be: a = 45, b = 30. Your code should print out a
final answer of 75.
234. Write a function called multiply_divide that multiplies
variables a by b and divides them with c. The function should
request the users' input on a, b, and c. If the user inputs (a = 45,
b = 60, c = 15), your function should return 180.0.
235. Write a function that asks people for their age. Name the
function your_age. Print out their age as "Your age is + [their
age ] + years old."

234 | Page
Python’s Variable Scope
236. What is a global variable?
a. A variable inside a function that can only be accessed
inside a function
b. A variable that can be accessed both locally and globally.
c. A variable that can be changed
d. A variable that is created inside of a function

237. Janet writes the following code:


def myfunction():
c = 200
return c
myfunction()

Janet wants to make the variable c into a global variable so it can


be accessed outside the function. What change should she make
to the function?
a. Create the variable outside the function
b. Use the global keyword inside the function to declare c a
global variable
c. Use the global keyword outside the function to declare c a
global variable
d. Delete the variable c and put it outside the function.

238. What is a local variable?


a. A variable that is declared inside a function and can only
be used in that function
b. A variable that is declared outside a function and can only
be used outside a function
c. A neutral variable
d. A variable that cannot be modified

235 | Page
239. Any variable declared outside a function is a global variable.
True or False?
a. True
b. False

240. A keyword "local" must be used with a variable in a function to


make it local. True or False?
a. True
b. False
241. Any variable declared inside a function is automatically a global
variable. True or False?
a. True
b. False

Error Handling
242. Which one of the following reserved keywords is used in error
handling?
a. del
b. try
c. False
d. True

243. All errors will crash the program if not handled. True or False?
a. True
b. False

244. Which one of the following correctly defines the purpose of the
keyword, except?
a. It deletes errors in the try block code
b. It handles the errors raised in the try block
c. It crashes the code when an error is discovered
d. It discovers errors in the code

236 | Page
245. Which one of the following keywords is used to raise
exceptions?
a. raise
b. finally
c. error
d. try
246. Which one of the following breaks down the finally keyword?
a. A code that runs only when there is no exception in the
code
b. A code that runs after a try block whether the exception is
handled or not
c. A code that deletes errors that are handled in the except
block of code.
d. A code that deletes the error raised in the try block of code
247. Jane writes the following code:
print(x)
The code generates an error and crashes the program because x
is not defined. Using the keywords try and except, write a code
that will handle the NameError generated by this code. The code
should print "x is not defined" when it encounters a NameError.
248. Mary writes the following code:
a = int(input("Enter a number"))
b = int(input ("Enter another number"))
print(a/b)

Mary is concerned that the program will crash if someone tries


to divide a number by zero (0). Make sure the code can handle
the ZeroDivisionError by using try and except. When a
ZeroDivisionError error occurs, it should print out "You cannot
divide a number by 0; try again."
249. Add a finally block to your code (question 248). The finally
block should print "End of code."
250. Modify your code (question 249) so that it can also handle
"ValueError". If someone enters something that is not a number,
print "You have not entered a valid number; try again."

237 | Page
251. For a cleaner code, your boss has asked you to put your code
(question 250) in a function. Create a function called divide for
your code. Make sure that your function runs until it returns the
results of the expression (the division of a and b).

252. Wendy wants to write a code to get a user’s age. She is worried
that people may enter invalid numbers like 0 or numbers above
150 for their age. Help her with a function called your_age that
will ask people to enter their age. The function should be able to
handle invalid inputs. If a person enters a number less than 1, the
code should print "You cannot enter a number that is less than 1;
try again." If someone enters a number that is above 150, the code
should say, "You cannot enter a number above 150; try again." If
someone enters a valid age, it should print "Your age is: + age +
years old."

Pip and Modules


253. What is a module in Python?
a. A function and statement in Python
b. A Python file that contains Python code
c. A Python library
d. Any Python code is a module
254. Which of the following is the correct way to name a module?
a. add .py at the beginning of the name
a. add .py at the end of the name
b. add _py at the end of the name
c. add py_ at the end of the name
255. Mary has created a function file named add.py. She wants to use
this function in a new file. Create code that will import this
module into her new file.

238 | Page
256. What is the difference between a module and a library?
a. A module is a collection of modules with different
functionalities, while a library is a module with single
functionality
b. There is no difference between a module and a library
c. A library is a collection of modules with different
functionalities, while a module is a file with different
functions
d. A module is a function, while a library is a statement

257. What is pip in Python?


a. A module in Python
b. A library in Python
c. A package manager in Python
d. A function in Python

258. Steward has found a library called pandas online and he wants
to use it in his data science project. How does Steward install
this library on his machine using pip? Do a little research for
Steward.

259. Sean writes the following code:


def add(x,y):
sum = x + y
return sum

Run this code and save it as add.py. Once it's saved, open
another Python file and import the module you have saved. Use
the module to find the sum of:
x = 23
y = 12
Print out the answer.

239 | Page
260. Jane wants to import only a certain function from a module
called add.py. She wants to import the sum function from the
module. Which is the correct syntax for importing this sum
function?
a. import sum
b. from add import sum
c. import sum from add
d. import add import sum
261. Dwayne wants to rename a module he wants to use in his file.
He wants to shorten the name. The name of the module is
myfunction.py. Dwayne wants to shorten the name to mf.
Which of the following is the correct way for Dwayne to import
and shorten the name of the module?
a. import mf
b. from myfunction import mf
c. import myfunction as mf
d. import mf as myfunction
262. Which one of the following functions is used to check the
attributes and methods in a module?
a. dir()
b. dy()
c. bin()
d. sin()

Dates in Python
263. Write a code to import time, date, and datetime from the
datetime module.
264. Write a code that prints out your current time in this format:
hours, minutes, and seconds. Use the now() method and
the datetime class from the datetime module. Create a
variable called x for your time.
265. Using the datetime class from the datetime module, print
today’s date, just the date. Create a variable called x for the date.
Print the date in this format: month, date, year. Use the
now() method.

240 | Page
266. Using the datetime class from the datetime module and the
today() method, create a variable x for your current time (use
this format: hour, minute). Print x.
267. Create a variable called x for the current date. Use the date
class from the datetime module and the today() method.
Print x.
268. Which one of the following datetime methods is used to
format time?
a. strptime()
b. strftime()
c. fromtimestamp()
d. timestamp()
269. This is Jack’s code:
import datetime
x = datetime.datetime(2021, 7, 1)
print(x.strftime("%G"))
What is the result of running this code by Jack?
a. July
b. 2021
c. 1
d. 2020
270. Jack makes a little change to the code:
import datetime
y = datetime.datetime(2021, 7, 1)
print(y.strftime("%A"))
What is the result of running this code?
a. Thursday
b. Wednesday
c. 2021
d. July
271. Write a function called "age" that calculates a user’s age. The
function should ask the user to enter their year of birth and
should return their age. The function should print "You are: +
user’s age + years old."

241 | Page
Lambda Functions
272. What is a lambda function?
a. A name of a function
b. An expression that has no particular meaning
c. An anonymous function or a function without a name
d. All functions with names are lambda functions

273. Which one of the following is not a characteristic of a lambda


function?
a. It can only take a limited number of arguments
b. It can only have one expression
c. It can be used in another function
d. It can take an unlimited number of arguments
274. Martha is using a lambda function in her code below:
v = lambda a,b,c: a*b*c*2
print(v(12,3,6))

What is the result of running this code?


a. 216
b. 432
c. 108
d. 864
275. Create a lambda function, variable name x, that takes two
arguments, a and b. It sums the two arguments and multiplies
them by 2. Print out the result of the code. (a = 10, b = 15). Your
result should be 50.
276. What is the result of running this code?
v = lambda a:a/2
print(int(v(12)))

a. 6.0
b. 12
c. 0
d. 6

242 | Page
277. What is the result of running this code?
v = lambda a:a%2
print(int(v(12)))

a. 6
b. 6.0
c. 0
d. 4

278. Kelvin has written code that uses a lambda function inside a
function:
def divide(num):
return lambda y : y / num

divide1 = divide(5)
print(divide1(20))

What is the result of this code?


a. 0.25
b. 4.0
c. 5
d. 6

279. Modify the code (question 278). Change the value of y to 50


and run the code. What is the new output?

280. Here is a list of exam results of students at a certain school:


results = [ 32, 45, 78, 67, 88, 97, 76, 84, 44, 66, 63,
86, 90, 80]

John wants the list filtered so he can know how many students
got over 60 marks. Using the filter() function and lambda
function, write a code that will show John how many students got
over 60 marks.
281. Write another code for John (question 280) that will show how
many students got less than 50 marks.

243 | Page
Python Classes
282. Python is usually referred to as an object-oriented
programming language. What does that mean?
a. It means everything in Python is a function with its own
properties
b. It is structured into objects of similar properties and
behaviors
c. It is not structured into objects of similar properties and
behaviors
d. It means it’s an easy language to learn

283. What does it mean to "create a class" in Python?


a. It means to create a function
b. It means to create a blueprint for creating objects
c. It means to create a variable
d. It means to create a database for your code

284. Jane wants to understand what an instance of a class is, so she


comes to you for help. Describe to Jane what an instance of a
class is.

244 | Page
285. What is the correct syntax for creating a class called "car"?
a. class Car:
b. (class car):
c. class car():
d. class_car:

286. What is the correct syntax to print out the variable i in the code
below?
class Cat:
i = 2

a. print(cat)
b. print(Cat)
c. print(i)
d. print(Cat.i)
287. What is the purpose of the constructor (__init__) function?
a. To create a class
b. To create an instance for a class
c. To assign values to class instances
d. To delete class objects
288. Which one of the following is a valid way to create a class
named "Car" with parameters: brand and model?
a.
class Car:
def __init__(self,brand, model):

b.
class Car():
def __init__(self,brand, model):

c.
class car:
def __init__(self,brand, model)

d.
class Car:
def (self, brand, model)

245 | Page
289. Which of the following is the correct way to assign instance
variables?
a.
class Car:
def __init__(self,brand, model):
self = model
self = model

b.
class Car:
def __init__(self,brand, model):
self.(brand) = model
self.(model) = model

c.
class Car:
def __init__(self,brand, model):
self(brand) = model
self(model) = model

d.
class Car:
def __init__(self,brand, model):
self.brand = brand
self.model = model

290. Continue with the code (from questions 288 and 289). Create an
object called "car1". The brand of the car is Nissan, and the
model is Murano. Print the model of the car1 object.

291. Create a second object (question 290) called "car2". The car
brand is Ford, and the model is Focus. Print the brand of the
car2 object.

292. Modify the car2 object you created (question 291). Change the
brand name from Ford to Honda and the model name from
Focus to Civic. Print the car2 model.

246 | Page
293. Write a code to delete the Car class (question 289–292).

294. Jonathan and John cannot agree on whether you can include a
function inside a class. Jonathan is saying you cannot put a
function inside a class and John is arguing the opposite. Who is
telling the truth?
a. Jonathan
b. John
c. None
295. What is the purpose of the destructor __del__() function?
a. To add an object
b. It is called when an object gets destroyed
c. To modify/collect the deleted object
d. To lock the object

296. What is inheritance in Python classes?


a. When a child class has a similar name to the parent
class
b. When one class inherits the methods and properties of
another class
c. When a child class is smaller than a parent class
d. When a parent class has the properties of a child class

297. Which one of the following functions is used by the child class to
inherit from the parent class?
a. __init__()
b. super()
c. def()
d. self()

247 | Page
298. Mary writes the following code. She wants you to add something
to the code.
class Father:
def __init__(self,firstname,lastname,age):
self.firstname = firstname
self.lastname = lastname
self.age = age

# instance method
def print_father(self):
print("Your first name is {} and your last name is {}."
"You are {} years old".
format(self.firstname, self.lastname, self.age))

# Creating the first object


father1 = Father("Richard", "Kelly", 42)

print(father1.print_father())

Create a second object—father2. The first name is Benson, the last


name is Carter, and the age is 52. Print father2 using the
print_father method.

299. Which one of the following codes is the correct way of creating a
child class named Son that inherits from the Father class (question
298)?
a.
class Son(Father):

b.
class Father(Son):

c.
class Son():(Father):

d.
class son(father):

248 | Page
300.Add a child class to the code (question 298). The name of the
child class is Son. The child class inherits from the parent class.
Create the child class and do not add any content to it (use pass
statement). Once the class is created, create an object of the child
class called son1 (First name: Shawn, Last name: Kelly, Age:
21) and use the print_father method (instance method) to
print out son1.

301. Modify your code (question 300) by adding a parameter to the


child class (Son class). Use the __init__() function to assign
'height' to the class. Ensure that the son class still inherits
properties and methods from the parent class. Create a new
instance method for the son class called print_son (similar to
print_father in the father class). The print_son function
(method) should print (return) what is printed by the
print_father method, but you should add "and your height is"
at the end. Modify the son1 object you just created in question
299 and add height to it (First name: Shawn, Last name: Kelly,
Age: 21, height 5’9). Use the print_son method (call method) to
print this out.

File Handling
302. Which one of the following keywords is used to open text files in
Python?
a. append()
b. read()
c. open()
d. extend()

303. You have a text file called names.txt. You want to open and read
this file. Write a code to open and read this file using the with
statement.
304. You want to create a text file called "animals." Use the open()
function and the with statement to create the file. Add an animal
called "Elephant" to your file (write "Elephant" on the file).

249 | Page
305. You want to add two names to the animals' file you have created
(question 304). Write a code to open and add names to your file.
Add "lion" and "tiger" to the file. Ensure that each animal is
added to a separate line. Use the with statement. You should
now have 3 animals on your file. Write another code to open and
read the updated file.

306. Which one of the following is true about the "w" mode in the
open() file method?
a. It will overwrite an existing file
b. It will not overwrite an existing file
c. It will append to an existing file
d. It will delete an existing file

307. Write code to create a text file called my_first_file using the
with statement. Write "This is my first line" on the file. Then
write another program to open and read your file.

308. Write code to open the file you created in (question 307). Append
a line at the end of the file, "This is my last line." Use the with
statement. Once you append, write another code to open and
read your file. Your file should have two lines on it.

309. Write a code to delete the file you have created (question 308).

250 | Page
Extra Challenges

310. Write a code that finds and prints out all the odd numbers in the
variable list below.
a = [1, 2, 4, 6, 7, 9, 11, 17, 23, 26, 27]

311. Write a code that finds and prints out even numbers from the
list.
a = [1, 2, 4, 6, 7, 9, 11, 17, 23, 26, 27]

312. Write a code that finds duplicates in the following list.


a = [1, 1, 3, 5, 6, 1, 3, 6, 7, 8, 9, 6, 8, 9]

Print out the duplicates.


313. Write a function called convert that converts hours to minutes.
The function should ask the user for input. The function should
return the number of hours converted into minutes. Ensure that
the code does not crash when a user inputs something that is
not a number (value error).
314. Create a simple calculator that adds, subtracts, divides, and
multiplies inputs from the user. Ensure that your code can
handle zero division errors and value errors.
315. Write a function called guess_num that asks a user to guess a
number between 0 and 10. The code should generate a number,
and the user should guess that number. If the user guesses a
number that is higher than the generated number, the code
should tell the user that their guess is too high. If the guess is
lower, the code should tell the user that the guess is too low.
When the user guesses correctly, the code should tell the user
that they have won. The code should run until the user guesses
the right number.

316. Write a code that sums all the elements in the following list.
Your code should add up to 78.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

251 | Page
317. Write a code that finds how many capital letters are in the string
below. Print out the total number of capital letters in the string.
str = 'This Is noT how wE writE A sentence'

318. Write a code that sums all the values in the following
dictionaries.
a = {"Men": 20,"women": 25}
b = {"children": 23,"students": 44}

319. Write a function called smallest_odd that returns the


smallest odd number from a list. The function should take one
argument, a list. Use the list below as a parameter. Your
function should return 13.
a = [17, 23, 13, 24, 25, 33, 71, 81, 30]

320. Write a function called center that returns the middle


character of a string. The function should take a string as an
argument. If the string has no middle character, it should return
"This string has no middle character". When you pass it the
string below, it should return "c".
a = 'welcome'

321. Jane has written the following code:


names = ['Peter', 'Peter', 'Peter', "Peter"]

Jane wants to write a code that will be able to check if all the
names in the list are the same. If the names are the same, the code
should return, "All the names in the list are the same." If they are
different, the code should return "The names in the list are not
the same." Write a code for Jane.

252 | Page
Answers to Practice Questions

253 | Page
Answers to Practice Questions
1.a
It’s a set of rules on how a Python code will be written
and interpreted.

Think of syntax as the grammar of a programming language. For


Python to understand what you want to do, you have to write code
in a "grammar" that it will understand. If the syntax or grammar is
not right, the program will generate an error because it will not
understand what you want it to do.
2.a
A reserved memory location for an object.

When you create a variable, you are reserving some space where
the object you have created can be saved. You assign it a point of
reference, which is the variable name. To access or use the object,
you have to call the variable. In the code below, to use 2, we need
to call on the variable x.
x = 2
3.b
False
You can start a variable name with either an uppercase letter or a
lowercase letter.
4.c
myname
A variable name is always on the left side of the equal (=) sign.

5.d
-fruit- = "Orange"
You cannot start a variable name with a dash. Python allows you
to start a name with an underscore "_" but not a dash "-".

254 | Page
6.b
False
Indentation tells Python that something is part of a block of code.
Your code will generate an error if you do not indent a piece of code
that is part of a block of code. Indentation is more than a
readability thing.
7.a
True
The indentation of the print(x) is telling Python that the code is
part of a block of code. However, these two lines of code are not a
block of code. They are independent lines of code. For this reason,
the print(x) should not be indented.
8.c
Number-seven
You cannot use a dash ( - ) in a variable name. However, you can
use an underscore ( _ ).
9.c
The variable name should not start with a number.
You cannot start a variable name with a number. This is forbidden
in Python. You can use digits inside the variable name but not as
the first character.
10.c
The name Peter should have been put in quotation
marks.
The object should have been put in quotation marks to tell the
interpreter that it is a string. That’s proper syntax.
11.c, e
My-name
My name
You cannot use a dash or leave space between characters when
creating a variable name.

255 | Page
12.a
False
False is a reserved word in Python. Reserved words are not to be
used as variables. If you do not believe me, run the code below. We
will use the reserved word as a variable name.
False = 67
print(False)

In the output, we get a syntax error because an object cannot be


assigned to a reserved keyword, False.
Output:
SyntaxError: cannot assign to False

13."List" is not one of the reserved words in Python. However, it is a


built-in function. As good practice, you should not use reserved
words and built-in function names as variable names. If John uses
the word as a variable, the code will run, but any reference to the
built-in function will not work.

In the example below, we have used the word "list" as a variable


name. When we try to use the built-in function list() to create a
list after using it as a variable name, it will not work; it will generate
an error. Check the output below. This is why it is bad practice to
use built-in function names as variable names.
list = 7
print(list)
# Creating a list using the keyword list, will not work
a = list((4,4))
print(a)
Output:
a = list((4,4))
TypeError: 'int' object is not callable

256 | Page
14.a
del
"del" is a reserved keyword that should not be used as a variable
name. If you use it, your code will generate an error.

15.b
print is a built-in function in Python so it should not be
used.
If you use print as a variable name, all references to the built-in
function will not work. Let’s try to use print as a variable name and
use the print function to see that it works.

print = 67
print(print)

The code generates an error because the print() function cannot


work anymore. It has been "overwritten" by the print variable.
Output:
TypeError: 'int' object is not callable
16.a
Variable names are case-sensitive so fruit is not equal to
Fruit.
To print fruit, Kelly needs to use the small-letter fruit in the
code.

17.c and d
Fruit = Mango
Fruit = int(Mango)
C and d are not strings. But if you check the class type of a and b,
they will be a strings.

257 | Page
18.c
print(c)
In Python, you can create multiple variables and assign multiple
values to them. The number of variables should equal the number
of objects. Otherwise, your code will generate an error. To access
the values, you need to access the variable that matches the
position of the value. In our example below, the variable a will
print out "alphabet" and the variable b will print out "banana" and
so forth.
a, b, c = "alphabet", "banana", "car"
print(c)
Output:
car

19.b
# This is a comment
In Python, comments are preceded by the hash #. If a comment is
written between three quotes ("""), then it is a docstring. See
below:
'''
This is a docstring comment in Python.

'''

20.a, b
car = "Toyota"
car = 'Toyota'
John can use either double quotes or single quotes to create a
string.
21.a
A statement is a line of code that does something while an
expression is a line of code that evaluates to something.
The following is an expression because it evaluates to something.
4 + 2
If we print this out, we get 6.
print(4 + 2)
Output:
6

258 | Page
A statement, on the other hand, only does something. It does not
evaluate anything, and it does not print out any results. The
following code is an example of a statement. It creates a function
(does something), but it does not evaluate anything. When you
print this out, you will not get any results.
def my_function():

22.c
‘firstname’ + ‘lastname’
Remember, an expression always evaluates into something. And,
when you print out an expression, it will give results.

Print('firstname' + 'lastname')
Output:
firstnamelastname

23.b, c, d
float
integer
complex
The three types of numeric data types in Python are float, integer,
and complex data types.
Float – A float is any number that has decimal points. The number
of decimal places does not matter. It can be a positive or negative
number.
Integer – An integer is any number that does not have any
decimal points. It can be a negative or positive number.
Complex – Complex numbers have both real and imaginary
numbers.

259 | Page
24.a
20
Any number without a decimal point is an integer in Python.
25.a.
float
y = 1.5
print(type(y))
Output:
<class 'float'>
26.a
str
name = "John"
print(type(name))
Output:
<class 'str'>
27.c
list
fruits = ["apples", "mangoes", "Oranges"]
print(type(fruits))

A list is enclosed in square brackets [ ].


Output:
<class 'list'>

28.c
set
Sets are enclosed in curly brackets.
apples = {"apples", "mangoes", "Oranges"}
print(type(apples))
Output:
<class 'set'>

260 | Page
29.c
tuple
fruits = ("mango", "orange", "lemon")
print(type(fruits))
Output:
<class 'tuple'>
30.b
list
cars = ["BMW", "Mazda", "Honda", False, 1,2,9,10]
print(type(cars))
Output:
<class 'list'>

31.b
bool
y = False
print(type(y))
Output:
<class 'bool'>

32.a
dict
A dictionary has a key and a value. "name" is a key and "Peter" is a
value. You can access the value through the key.
y = {"name": "Peter", "school": "yale"}
print(type(y)
Output:
<class 'dict'>

33.a
Converting one data type into another using a Python
function.
We can use a Python function to convert one data type into
another. In the example below, we are converting a float into an
integer using the int( ) function.
y = 1.5
y = int(y)
print(type(y))

261 | Page
When we print out the data type of y, we can see from the output
that the float has been converted into an integer class.
Output:
<class 'int'>

34.a
5.0
In this code, Mary is trying to convert an integer into a float using
typecasting. If you run the code below to check x type, you will get
a floating class. Remember that a floating number has a decimal
point.
x = 5
x = float(5)
print(x)
Output:
5.0
35.
The code below converts x into an integer using the int function:
x = "10"
x = int(x)
print(type(x))
Output:
<class 'int'>
36.
Using the str() function, we can convert an integer into a string.
x = 10
x = str(x)
print(type(x))
Output:
<class 'str'>

262 | Page
37.
The code to convert an int to a float using the float() function:
x = 23
x = float(x)
print(type(x))
Output:
<class 'float'>
38.b
y = str(y)
The str() function will convert y into a string.
39.b
4
The int() function will convert a float into an integer. It will
disregard decimal points.
40.
It is possible to create a tuple with one element. However, if you
create a tuple with one element like the one below, and you check
the data type of your variable, it will not be a tuple but a string. See
below:
z = ("a")
print(type(z))
Output:
<class 'str'>

To create a one-element tuple, we need to add a comma in front


of the element. Check below:
z = ("a",)
print(type(z))
Output:
<class 'tuple'>
Another way to create a one-element tuple is to use the tuple
keyword if you do not want to use the comma. Check below:
z = tuple("a")
print(type(z))
Output:
<class 'tuple'>

263 | Page
41.
Using the round brackets, we can create a tuple like this:
names = ("Jane", "Mary", "Alice")
print(type(names))
Output:
<class 'tuple'>

42.
We can use indexing to access the elements in a tuple since tuples
are ordered. To access "Alice," we can use this code:
names = ("Jane", "Mary", "Alice")
print(names[2])
Output:
Alice

43.
We can use the keyword len() to check the length of our tuple. The
code will return the number of elements in our tuple.
names = ("Jane", "Mary", "Alice")
print(len(names))
Output:
3

44.
Tuples are immutable. They cannot be changed once they are
created. However, you can create a new tuple by copying the
contents of a tuple and concatenating them with the content of
another tuple. The first thing is to create a new tuple with a single
element, "Maria."
new_name = ("Maria",)

We can now concatenate the tuple to our old tuple and create a
new tuple.
names = names + new_name
print(names)
Output:
('Jane', 'Mary', 'Alice', 'Maria')

264 | Page
45.
Since tuples are not mutable, we cannot remove an item from a
tuple we have created. We can only create a new tuple that will not
have the name Maria in it. The easy way to do this is to use
indexing. Let’s create a variable called names_2.
names_2 = names[:3]
print(names_2)
Output:
('Jane', 'Mary', 'Alice')

46.
Using the count() function, we can check the number of times the
name "Jane" appears in our tuple of names. We can see from the
output that Jane only appears once. We are using the name "Jane"
as the argument.
print(names.count("Jane"))
Output:
1

47.c
index()
The index() method returns the position of a particular item in
the tuple. It is possible to use the indexing method because tuples
are ordered. In the example below, we use the index() method to
search for the position of "Alice" in the tuple.
names = ("Jane", "Mary", "Alice")
print(names.index("Alice"))

We can see from the output the position of "Alice" in our tuple.
Remember that the index starts at 0. In the tuple of names, "Jane"
is position 0, which means "Alice" is position 2.
Output:
2

265 | Page
48.d
There is no limit to the number of items you can add to a
tuple.
Tuples can have duplicate values and they can take Boolean values.
Tuples can also combine different data types at the same time.
There is no limit to the number of items a tuple can take.
49.
Here is what happens when we try to create a tuple of
colors:
colors = tuple( "Red", "Bue", "Green")
print(colors)
Output:
colors = tuple( "Red", "Bue", "Green")
TypeError: tuple expected at most 1 argument, got 3

Creating a tuple using the tuple() constructor is only possible if


our tuple will contain only one element. To get around this, we
need to add double brackets to our tuple. Let’s make some changes
below:
colors = tuple (("Red", "Bue", "Green"))
print(colors)

You can see below that our tuple has no errors.


Output:
('Red', 'Bue', 'Green')

50.a, d
Tuples have ordered values, while sets don’t.
Tuples are immutable while sets are mutable.

266 | Page
51.a
x is a tuple, y is a set
Remember, a tuple has round brackets while a set has curly
brackets.
52.False
You cannot use the sort() method to sort a tuple because it is
immutable. The position of the items does not change. However,
there is a way around it. We can use the sorted() function to sort
a tuple. This function returns a list. We will then have to convert
the list back to a tuple. See the example below:
# A tuple of numbers
num = (1,2,9,8,5,78,45)

# using the sorted function to sort the tuple


num2 = sorted(num)
print(num2)
Output:
[1, 2, 5, 8, 9, 45, 78]
We can now convert the list back to a tuple using the tuple()
function.
# Converting a list to a tuple
num2 = tuple(num2)
print(num2)
Output
(1, 2, 5, 8, 9, 45, 78)
53.b
Yes, you can have duplicates in the tuple.
The tuple below has two "Greens."
colors = tuple(( "Red", "Bue", "Green","Green"))
print(colors)
Output:
('Red', 'Bue', 'Green', 'Green')
54.a
print(len(animals))

267 | Page
55.d
Tuples are immutable
If we want to update a tuple, we will have to create a new one.
We cannot update a tuple once it is created.
56.c
Impossible to delete an item from a tuple.
We cannot delete an item from a tuple because they are not
mutable. Tuples are permanent. The only way around it is to
convert the tuple into a list, use the list method to remove the item,
and then convert the list back to a tuple.
57.
We can combine the two tuples using the addition (+) operator and
create a new tuple.
animals = ("dog", "cat", "duck", "chicken")
fruits = ("oranges", "apples", "mangoes", "bananas")

animals_and_fruits = animals + fruits


print(animals_and_fruits)
Output:
('dog', 'cat', 'duck', 'chicken', 'oranges', 'apples',
'mangoes', 'bananas')

58.
We can use multiplication to double the contents of a tuple. We can
create a new tuple. Multiply the tuple by 2.
cars = ("BMW", "Isuzu", "Nissan")
cars2 = cars*2
print(cars2)
Output:
('BMW', 'Isuzu', 'Nissan', 'BMW', 'Isuzu', 'Nissan')

59.c
count()
The only tuple methods are count() and index().

268 | Page
60.c
list
List properties:
Lists are ordered.
Lists allow for duplicate values.
Lists are not immutable, that is they can be changed once they are
created.
61.
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(type(numbers))
Output:
<class 'list'>
62.
Using slicing we can print the numbers
numbers = [10, 20, 40, 70, 60, 90, 100, 55, 78, 89]
# Using slice to print out the numbers
print(numbers[3:-5])
Output:
[70, 60]

63.
numbers = [10, 20, 40, 70, 60, 90, 100, 55, 78, 89]
# Using slice to print out the numbers
print(numbers[3:-3])
Output:
[70, 60, 90, 100]

64.
Using the sort() method, we can change the position of the items
in the list because lists are mutable.
numbers = [10, 20, 40, 70, 60, 90, 100, 55, 78,89]
# using sort() to sort the list in ascending order
numbers.sort()
print(numbers)

By default, the sort() method sorts the list in ascending order.


Output:
[10, 20, 40, 55, 60, 70, 78, 89, 90, 100]

269 | Page
65.b
False
Even though, by default, the sort() method sorts the list in ascending
order, you can also sort a list in descending order. To sort a list in
descending order, set the reverse parameter to True.

numbers = [10, 20, 40, 70, 60, 90, 100, 55, 78,89]
#set reverse to true to sort in descending order
numbers.sort(reverse=True)
print(numbers)
Output:
[100, 90, 89, 78, 70, 60, 55, 40, 20, 10]

The sort() method can also be used to sort out words:


cars = ["BMW", "Isuzu", "Nissan"]
cars.sort(reverse=True)
print(cars)
Output:
['Nissan', 'Isuzu', 'BMW']

If you set reverse = False, you will sort the list in ascending order.
cars = ["BMW", "Nissan", "Isuzu"]
cars.sort(reverse=False)
print(cars)
Output:
['BMW', 'Isuzu', 'Nissan']

66.c
return()
Return is not a list method in Python. The rest are list methods.
67.b
2
This code checks how many times the item "Toyota" appears in the
list. It uses the list method count(). Toyota appears in the list 2
times; hence the code returns 2.

270 | Page
68.d
print(cars[3])
Remember that in Python, counting starts at zero (Index 0). The
"BMW" in the list is at position zero.
cars = ["BMW", "Honda", "Nissan", "Toyota"]
print(cars[3])
Output:
Toyota

69.c
It is immutable
Lists are not immutable. You can delete, change, add, and sort items
in a list. Lists are ordered.

70.
Using the del statement and indexing, we can remove the items
from the list.
a = [1,2,4,4,5,6,7,8,9]
# Using the del method to remove the items
del a[2:5]
print(a)
Output:
[1, 2, 6, 7, 8, 9]

71.a
print(len(a))
a = [1, 2, 4, 4, 5, 6, 7, 8]
print(len(a))
Output:
8
72.b
drop
"Drop" is not a list method.

271 | Page
73.b
girls_names.pop()
By default, pop() will remove the last item in the list. You can also
pass the index of the item that you want to be removed.
girls_names = list(("Mary", "Rose", "Kate", "Amanda"))
print(girls_names.pop())
Output:
Amanda
74.b
append()
Append adds an item at the end of the list.
Let’s use the append() method to add another item to our list. We
will add the name "Jane" to our list.
girls_names = list(("Mary", "Rose", "Kate",
"Amanda"))

# use append to add Jane to the end of the list


girls_names.append("Jane")

print(girls_names)
Output:
['Mary', 'Rose', 'Kate', 'Amanda', 'Jane']
75.b
append adds a single item to the list, while extend
increases the list by the number of items in an iterable.
In the following example, we extend list a with list b using extend()
method.
a = [1, 2, 4, 4, 5, 6, 7, 8]
b = [9, 10, 11, 12, 13, 14, 15, 16]
a.extend(b)
print(a)
Output:
[1, 2, 4, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

On the other hand, using append() will only extend the list by one
item, the other list.

272 | Page
a = [1, 2, 4, 4, 5, 6, 7, 8]
b = [9, 10, 11, 12, 13, 14, 15, 16]
a.append(b)
print(a)

You can see from the output below that the whole list b has been
appended to list a. We now have a nested list.
Output:
[1, 2, 4, 4, 5, 6, 7, 8, [9, 10, 11, 12, 13, 14, 15, 16]]

76.b
BMW and Toyota.
cars = ["Volvo", "Honda", "BMW", "Toyota"]
cars[2:4] = ["Audi","Ford"]
print(cars)
Output:
['Volvo', 'Honda', 'Audi', 'Ford']

77.d
cars[-4]= "Benz"
With negative indexing, you are counting from right to left.
Here is the code below:
cars = ["Volvo", "Honda", "BMW", "Toyota"]
cars[-4]= "Benz"
print(cars)
Output:
['Benz', 'Honda', 'BMW', 'Toyota']

78.a
0
The index finds the position of "Volvo" in the list. Remember that
indexing in Python starts at 0. A Volvo is sitting at position zero.
79.b
sorted()
Sorted() is not a list method. It is a built-in function. It can work
with lists and other data types like tuples.

273 | Page
80.
Sorted() is a built-in function. It’s not a list method, so it can
stand on its own.
x = [1, 3, 5, 7, 8, 9, 2, 4, 5, 7, 10]
y = sorted(x)
print(y)
Output:
[1, 2, 3, 4, 5, 5, 7, 7, 8, 9, 10]

81.c, d
You can change sets after they are created.
Sets are surrounded by curly brackets.
Sets are not ordered, they do not allow duplicates, but they can be
modified.
82.
Here is a set below. Remember to use curly brackets for sets.
Print out the data type using the type() function.
cars = {"Benz", "Ford","Toyota"}
print(type(cars))
Output:
<class 'set'>

83.
You cannot replace Toyota with Honda once the set is created. You
can only add new items to the set and remove items, but you cannot
replace items in the set. The only way around it is to create a new
set.

274 | Page
84.
We can use the update() method to merge the two sets.
set1 = {10, 67, 90, 91, 77, 73}
set2 = {2, 1, 4, 6, 8, 7}
#merge the set2 to set1 using the update method
set1.update(set2)
print(set1)

The output is a set that contains combined elements.


Output:
{1, 2, 67, 4, 6, 7, 73, 10, 77, 90, 91}

85.
Using the remove() method, we can remove the 77 from set1
set1 ={1, 2, 67, 4, 6, 7, 73, 10, 77, 90, 91}
set1.remove(77)
print(set1)
Output:
{1, 2, 67, 4, 6, 7, 73, 10, 90, 91}

86.b
method()
87.
We can use the clear() method to remove all elements from the
set.
v = {12, 90, 89, 23, 56}
v.clear()
print(v)
The output is an empty set.
Output:
set()

275 | Page
88.
Using the set() constructor we can create a set. Take note of the
double brackets. The set() constructor takes one argument that’s
why we put everything in brackets before calling the constructor.
num_set = set((1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
print(type(num_set))
Output:
<class 'set'>

89.
We use the len() method to check the number of elements in a set
num = set((1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
print(len(num))
Output:
10

90.a
True
You cannot replace items once a set is created, but you can add new
items using the add() method and the update() method. The
add() method only adds one item at a time to the set. You can also
remove items using the remove() method.

Here is an example below. We added 11 to the num set using the


add() function.
num = set((1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
num.add(11)
print(num)
Output:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}

91.
Let’s use examples to demonstrate the difference between the two
methods.
Update() method
The update() method updates the original set with the content of
the new set. See the example below.

276 | Page
set1 = {10, 67, 90, 91, 77, 73}
set2 = {2, 1, 4, 6, 8, 7}
set1.update(set2)
print(set1)
Output:
{1, 2, 67, 4, 6, 7, 8, 73, 10, 77, 90, 91}

Union () method
The union() method combines two sets to create a new set that
contains elements from both sets. See the example below:
set1 = {10, 67, 90, 91, 77, 73}
set2 = {2, 1, 4, 6, 8, 7}
set3 = set1.union(set2)
print(set3)
Output:
{1, 2, 67, 4, 6, 7, 8, 73, 10, 77, 90, 91}

92.c
Sets have a similar bracket type to dictionaries.
Both sets and dictionaries use curly brackets.
93.
We can use the update() method to add cars2 to cars 1.
cars = {"Volvo", "Honda", "BMW", "Toyota"}
cars2 = {"Audi","Ford"}
cars.update(cars2)
print(cars)

We can see from the output that elements of car2 have been added
to cars.
Output:
{'Ford', 'BMW', 'Honda', 'Toyota', 'Volvo', 'Audi'}

94.b
The plus sign + is used to add values together.
You can use the plus sign to add values together and concatenate
strings.

277 | Page
95.b
8
This is an exponentiation sign (double *).
This expression is equivalent to 2 * 2 * 2.
x = 2**3
print(x)
Output:
8

96.c
36
The breakdown of this code is as follows:
6 * 3 = 18
18* 2 = 36
y = 6 * 3
print(y*2)
Output:
36

97.b
/
This is a division operator.
The division operator will always return a floating number. Here is
an example below:
y = 6 / 3
print(y)
Output
2.0

278 | Page
98.d
2
This is a floor division (//) sign. It rounds the answer to the nearest
round number.
6 / 4 = 1.5, however, since we are using the "//" sign the 1.5 will be
rounded off to 1. When we multiply 1 by 2 (using the * sign), we get
2.
x = 6//4
print(x*2)
Output:
2

99.c
3.0
This is a division sign (/). When you divide 6 by 4, you get 1.5.
Multiply 1.5 by 2, and you get 3.0. Remember that a (/) sign will
always return a floating number; that is why we are getting 3.0 as
an output.
x = 6/4
print(x*2)
Output:
3.0

100.b
//operator returns the result without decimal places,
while / operator returns the results with decimal places.
This operator (//) rounds off the division to the nearest whole
number.
x = 6//4
print(x)
Output:
1
This operator (/) returns the result of division with decimal
points. See below:
x = 6/4
print(x)
Output:
1.5

279 | Page
101.b
c += 5
This is the shorthand method of c = c+ 5.
102.b
0
The modulus (%) operator returns the remainder of the division.
In this case, the result is zero.
b = 12%3
print(b)
Output:
0
103.d
equal
This is not a logical operator. The rest are logical operators in
Python.
104.a
True
The expression is simply checking if 10 is NOT equal to 5, and,
indeed, 10 is not equal to 5.
105.c
Y //=5
106.b
A sequence of characters surrounded by quotation
marks.
A string in Python is surrounded by quotation marks. You can
use double or single quotation marks. The codes below are the
same.
x = 'car'
x = "car"

280 | Page
107.b
False.
Split() splits the string at a specified separator and returns a
list of strings from the string. Check the example below:
fruits = "mangoes oranges"
print(fruits.split())
Output:
['mangoes', 'oranges']

Strip() trims a string by removing any space or specified


characters at the beginning and the end of a string.
fruits = "$mangoes oranges$"
print(fruits.strip("$"))
Output:
mangoes oranges

108.d
y = 5.
A string is created by using double quotation marks, single
quotation marks, and the keyword str(). From the codes below,
you can see that the output for y = 5 is int().
y = str(5)
print(type(y))
y = '5'
print(type(y))
y = "5"
print(type(y))
y = 5
print(type(y))
Output:
<class 'str'>
<class 'str'>
<class 'str'>
<class 'int'>

109.c
print(y[5: 13])
Here is the code below:
y = "I am learning python"
print(y[5: 13])
Output:
learning

281 | Page
110.a
print(y[-6:]).
Here is the code below. Remember to start counting from right to
left.
y = "I am learning Python"
print(y[-6:])
Output:
Python

111.
We are going to use the replace() method to replace the word in
our string.
y = "I am learning python"
y = y.replace("learning", "studying")
print(y)
Output:
I am studying python

112.
We can use the strip() method to remove the characters.
fruits = "#mangoes, oranges#"
print(fruits.strip('#'))
Output:
mangoes, oranges

113.b
He cannot use double quotes inside a string surrounded
by double-quotes.
Dwayne should have used single quotes inside the string. Check
the example below:
y = "I don’t like 'lazy' people"
print(y)
Output:
I don’t like 'lazy' people
Another way around it is to use escape characters inside the
string. That way, you can still use double quotes inside the string.
See the example below:
y = "I don’t like \"lazy\" people"
print(y)
Output:
I don’t like "lazy" people

282 | Page
114.a
capitalize()
Here is an example to capitalize a y variable
y = "ben"
print(y.capitalize())
Output:
Ben

115.a
lower()
Example below:
x = "Ben"
print(x.lower())
Output:
ben

116.a
upper()
The code below demonstrates how the upper() method converts
the whole string to upper case.
y = "i love ben"
print(y.upper())
Output:
I LOVE BEN

117.b
len()
Remember, Python counts the characters. The space between
words is counted as a character.
y = "i love ben"
print(len(y))
Output:
10

283 | Page
118.c
\n
Here is the example below. In this code, we are telling Python to
write "Ben" in another line. You can see in the output that Ben is
in another line.
y = "I love \nBen"
print(y)
Output:
I love
Ben

119.b
True
The code will return True because a is a bool() value.
120.a
True
7 is greater than (7-1).
121.b
True
The Insinstance () function checks if the variable home is a
string or not. In this instance, it is a string. That is why it returns
true. If we replace "str" with "int", it will return false because the
variable home is not an integer but a string. See below:
home = "The place where I relax"
print(isinstance(home, int))
Output:
False
122.a
student = {"name": "John", "age": 23}
A dictionary has curly brackets and has a key-value pair. In the
dictionary above, "name" is a key and "John" is a value.
123.a
Immutable.
Dictionaries are not immutable. You can change the values of a
dictionary.

284 | Page
124.a
print(cars.values()).
Here is the code below. The code prints out the values of the
dictionary.
cars = {"name": "Ford", "year": 1992}
print(cars.values())
Output:
dict_values(['Ford', 1992])

125.
Here is the code below. The code prints out the keys of the
dictionary.
cars = {"name": "Ford", "year": 1992}

for keys, values in cars.items():


print(keys, values)
Output:
name Ford
year 1992

126.a
cars["name"] = "BMW"
You can see from the output of this code that the car name has
changed from Ford to BMW. The new dictionary has BMW as a
value.
cars = {"name": "Ford", "year": 1992}
cars["name"] = "BMW"
print(cars)
Output:
{'name': 'BMW', 'year': 1992}

127.d
Keys cannot be changed.
Dictionary keys cannot be changed once they are made. The values
of the keys can be changed.

285 | Page
128.
Here is the code below:
cars = {"name": "Ford", "year": 1992}
cars ["color"] = "White"
print(cars)
Output:
{'name': 'Ford', 'year': 1992, 'Color': 'White'}

129.
Here is the code below:
cars = {"name": "Ford", "year": 1992}
cars ["year"] = 2004
print(cars)
Output:
{'name': 'Ford', 'year': 2004}

130.b
update().
131.
You can remove a key from a dictionary using the pop() method.
Pass the key that you want to remove as an argument.
cars = {"names": "Nissan", "year": 2007}
cars.pop('year')
print(cars)
You can see from the output that the key and its value have been
removed from the dictionary.
Output:
{'names': 'Nissan'}

132.
Alison can use the del statement to delete the dictionary. You can
see below that trying to print "cars" after running del generates an
error because "cars" has been deleted.
cars = {"names": "Nissan", "year": 2007}
del cars
print(cars)
Output:
NameError: name 'cars' is not defined

286 | Page
133.
We are going to create a dictionary called "students" that will be
nested. When we run print students, you can see that we get a
dictionary with dictionaries in it. This is a nested dictionary.

Student1 = {"name": "John", "grade" : "F"}


Student2 ={ "name" : "Alison", "grade" : "B"}
Student3 = {"name" : "Ben", "grade" : "C"}

students ={"Student1": Student1, "student2":


Student2,"student3":Student3}
print(students)
Output:
{'Student1': {'name': 'John', 'grade': 'F'}, 'student2':
{'name': 'Alison', 'grade': 'B'}, 'student3':
{'name': 'Ben', 'grade': 'C'}}

134.
Using the keyword pop(), Mary can specify which dictionary she
wants to remove from the nested dictionary. In this case, she wants
to remove student3. Here is the code below:
students = {'Student1': {'name': 'John', 'grade': 'F'},
'student2': {'name': 'Alison', 'grade': 'B'},
'student3': {'name': 'Ben', 'grade': 'C'}}
students.pop('student3')
print(students)

If we print this dictionary now, you will see that student3 has
been deleted.
Output:
{'Student1': {'name': 'John', 'grade': 'F'}, 'student2':
{'name': 'Alison', 'grade': 'B'}}
135.d
clear()
The clear() method will remove contents from the dictionary.
Let’s use our previous question as an example to demonstrate
this. When we try to print the dictionary after running clear(),
we get an empty dictionary.

287 | Page
students = {'Student1': {'name': 'John', 'grade': 'F'},
'student2': {'name': 'Alison', 'grade': 'B'},
'student3': {'name': 'Ben', 'grade': 'C'}}

students.clear()
print(students)
Output:
{}
136.b
newdict = mydict.copy()
If we run the code below, we can see that a copy of the mydict
dictionary has been created.
mydict = {"name": "Mary", "occupation": "Singer"}
newdict = mydict.copy()
print(newdict)
Output:
{'name': 'Mary', 'occupation': 'Singer'}
137.
The code below uses the get() method to access the value. You will
have to pass the key of the value you are trying to access to the
get() method.
mydict = {"name": "Mary", "occupation": "Singer"}
print(mydict.get("occupation"))
Output:
Singer

138.b
delete()
delete() is not dictionary method.
139.b
Dictionaries allow duplicate values.
Dictionaries allow duplicate values but not duplicate keys. If you
have two keys with the same name in a dictionary, then one of the
keys will be ignored. Let’s see the example below. The dictionary
below has two keys called "name." When we print the dictionary,
only the second key, called "name," and its value are printed. The
first one is ignored.
car = {'name': 'Honda', 'name':
'Ford', 'city': 'Tokyo'}
print(car)
Output:
{'name': 'Ford', 'city': 'Tokyo'}

288 | Page
140.b
Items in a dict are accessed by keys while items in a
list are accessed by referencing their position.
141.
x = { "name": "carol", "age": 23, "school": "Yale"}
print(x['school'])
Output:
Yale

142.
They are both mutable.
Dictionaries and lists can be changed after they are created.
143.a
Dictionary is mutable while a tuple is immutable.
144.
Here is the code below to loop through the dictionary.
x = { "name": "carol", "age": 23, "school": "Yale"}
for items in x.values():
print(items)
Output:
carol
23
Yale

145.
x = { "name": "carol", "age": 23, "school": "Yale"}
for items in x.keys():
print(items)
Output:
name
age
school

289 | Page
146.
The expression "name in x" will return a Boolean value. It will
return true if the key is in the dictionary and false if the key is not
in the dictionary.
x = { "name": "carol", "age": 23, "school": "Yale"}

if 'name' in x:
print('name is one of the keys')
else:
print('name is not one of the keys')
Output:
name is one of the keys

147.We can combine the two dictionaries using the Bitwise (|) OR
operator.
a = {'name': 'John', 'age': 25}
b = {'school': 'Yale', 'location': 'USA'}

c = a | b
print(c)
Output:
{'name': 'John', 'Grade': 11, 'school': 'yale',
'location': 'USA'}
148.b
A block of code that performs a specific task and runs
when called.
A function will only run when it is called.

149.b
def
Every function block in Python will start with the keyword def.

150.b
def my_car():

290 | Page
151.a
Values that are passed into a function when it is called.
Arguments are passed inside the paranthesis of the function. The
code below has two parameters between the round brackets, a and
b. When you call the function, you will have to pass two arguments
to a and b.
def add(a,b):

152.b
def car(carname):
153.
The parameters of the function will be put between the brackets.
def add(number1,number2):
sum = number1 + number2
return sum
print(add(5,7))
Output
12
154.c
def my_function (car = "BMW"):
The significance of a default argument is that whenever you call the
function and you do not pass an argument, it will use the default
argument.
When we call the function below, in the first code we pass "Honda"
as an argument, and the code prints out "Honda." In the second one,
we do not pass an argument, and the function prints out BMW,
which is our default argument.

def my_function (car="BMW"):


print("My favorite car is:" + car)

# Calling the function


my_function("Honda")
my_function()
Output:
My favorite car is: Honda
My favorite car is: BMW

291 | Page
155.a
To tell the function to return the results of the function.
In the example below, the return statement is telling the function
to stop and return the results of the function (number1 +
number2).
def add(number1,number2):
return number1 + number2
print(add(12,65))
Output:
77

156.d
All the above.
157.
Here is the code below:
def multiply_divide(a,b,c):
results = a*b/c
return results
print(multiply_divide(12,24,8))
Output:
36.0

158.c
A function can accept zero parameters.
A function does not require parameters to work. It is possible to
create a function with zero parameters. The function below has
zero parameters.
def myFunc():
print("My name is John ")

myFunc()
Output:
My name is John

292 | Page
159.b
She’s right we can use different arguments for one
function.
A function is powerful because you can use different arguments
for its parameters every time it is called. For example, for the
function below, we can use different arguments for a, b, and c
every time we call the function and it will still work. Functions
help in writing clean code by ensuring we avoid repeating code.
Instead of repeating code, we just call the same function and we
can use different arguments.

def multiply_divide(a,b,c):
results = a*b/c
return results

print(multiply_divide(12,24,8))
Example 2
def multiply_divide(a,b,c):
results = a*b/c
return results

print(multiply_divide(16,14,6))
160.b
Pass *args as the parameter of the function.
By using *args as a parameter name, you can pass any number of
arguments into the function.
In the example below, we have passed 3 arguments into the
function. You can change the number of arguments and it will still
work.
def myFunc(*args):
return "His cars are " + str(args).strip('()')

print(myFunc("BMW","Honda","Benz"))
Output:
His cars are 'BMW ', 'Honda ', 'Benz '

293 | Page
161.d
There is no limit to the number of parameters a function
can take.
You can pass as many parameters as you want into a function.

162.b
The sub1 and return should have been indented.
Indentation is a way of telling the interpreter that a piece of code
is part of a block of code. All codes that are part of the function
must be indented. If not, the code will generate an indentation
error. Python uses four spaces for indentation.

Below is how the code should be written with proper indentation.


def subtract(num1,num2):
sub1 = num1 - num2
return sub1
print(subtract(24,26))
This code is no longer generating an error.
Output:
-2

163.b
Declare the variable, a global variable.
Here is an example of that below. In this example, we have a
variable f inside a function.
def my_fun():
f = 12
sum = f + b
return sum
print(my_fun())

Let’s see what happens when we try to use the f variable outside
of the function.
sub = 23 - f
print(sub)
The code generates an error because the variable f is inside a
function. See below.
Output:
NameError: name 'f' is not defined

294 | Page
To use the f variable outside the function, we need to use the
global keyword inside the function. Let’s add global to the
function.
def my_fun():
global f
f = 12
sum = f + b
return sum
print(my_fun())
Now let’s use it outside the function.
sub = 23 - f
print(sub)
Now it works. Check the output below.
Output:
11
164.b
After my_func(), there is no colon (:)
This is how the code should have been:
def my_fun():
sum = 11 + 11
return sum
print(my_fun())

165.b
A variable declared inside a function.
In the code below, the x variable is a local variable because it is
declared inside a function and can only be accessed inside the
function.
def my_fun():
x = 1
166.c
print(subtract(10,5))
Here is the code below. We use the name of the function
"subtract" to call the function.
def subtract(num1, num2):
sub1 = num1 - num2
return sub1
print(subtract(10, 15))
Output:
-5

295 | Page
167.a
Add the keyword pass to the function.
Use the keyword pass when you want to create a function but are
not yet sure what to add to it. The pass keyword simply tells the
code to do nothing. When Python sees a pass statement, it will
not run the code.
def my_function():
pass
168.
Here is the code below:
def convert(km):
miles = km * 0.621371
return str(round(miles)) + ' miles'

print(convert(109))
Output:
68 miles

169.
Here is the code below:
def rectangle_area(a,b):
area = (a * b) * 2
return area

print(rectangle_area(15,67))
Output:
2010
170.
Here is the code below:
def area_of_triangle (base, height):
area = (base * height)/2
return area

print(area_of_triangle(24,67))
Output:
804.0

296 | Page
171.
def max_num(a):
if a < 10:
return "Max is less than 10"
else:
return "The number is not less than 10"
print(max_num(12))
Output:
The number is not less than 10

172.b
The print statement is not indented.
Indentation is important in Python. The print line is part of the if
statement block; that is why it should be indented.
a = 11
b = 10
if a != b:
print("it’s not equal")
Output:
it’s not equal
173.b
elif statement
The first statement is the if statement. The second condition
should use the elif statement. Elif is shorthand for "else if". The
last conditional statement is else.
174.
a = 10
b = 20

if a > b:
print("a is greater than b")
elif a < b:
print("b is greater than a")
else:
print("The two numbers are equal")
Output:
b is greater than a

297 | Page
175.
a = 22
b = 34

if b > a:
print("B is superior to A")
elif b < a:
print("A is superior to B")
Output:
B is superior to A

176.a
and
If a statement has two conditions, you can use the keyword
"and." Here is the example below.
if a > b and b < c:
177.
In this example, we are using the "and" keyword in our
conditional statement.
a = 12
b = 15
c = 18

if a > b and c > b:


print("Life is not fair")
else:
print("Life is beautiful")
Output:
Life is beautiful

298 | Page
178.
In this conditional statement, we are using the or operator. Both
conditions in the if statement are false, that’s why the else block is
executed.
a = 22
b = 34
c = 56

if a > b or b > c:
print("Life is good")
else:
print("Life is great")
Output:
Life is great

179.
if a > b or a > c: print("Life is good")

180.b
or
This is a reserved keyword used in conditional statements.
181.c
A loop that iterates over a given sequence of items.
A for loop will iterate over a string, a list, and so forth. Anything
that has a sequence of items can be iterated over by a for loop.
182.
Here is the code below:
a = "string"
for letters in a:
print(letters)
Output:
s
t
r
i
n
g

299 | Page
183.
Here is the code below:
animals = ("dog", "cat", "duck", "chicken")
for animals in animals:
print(animals)
Output:
dog
cat
duck
chicken

184.c
break.
The break statement breaks the loop. It stops the loop.
185.
Remember that a for loop iterates from left to right. In the
following code, we are telling the loop to stop the iteration once it
prints "Honda".
cars = ["Volvo", "Honda", "BMW", "Toyota","Toyota"]

for car in cars:


print(car)
if car == "Honda":
break
Output:
Volvo
Honda

186.b
continue

187.b
To stop the current iteration and begin a new one.
The continue statement tells the loop that once it reaches a
particular item, it should stop, skip that item, and start a new
iteration.

300 | Page
188.
In the following code, we are using the continue statement to tell
the loop that if it reaches "BMW," it should skip it and continue to
the next item.
cars = ["Volvo", "Honda", "BMW", "Toyota","Toyota"]

for car in cars:


if car == "BMW":
continue
print(car)

From the output below, you can see that we do not have a BMW
in the list.
Output:
Volvo
Honda
Toyota
Toyota

189.d
0,1,2,3,4
We are telling the loop to break or stop once it finds 5 in the
iteration. So, five will not be printed.
190.d
0,1,2,3,4,6,7,8,9
In this loop, the continue statement is telling the loop that once it
finds 5 in the iteration, it should skip it and continue with the next
item. So, 5 will not be printed.
191.a
Mary, John, Peter.
We are printing the values from the dictionary, which are Mary,
John, and Peter.

301 | Page
students ={"Student1": "Mary", "student2":
"John","student3":"Peter"}
for x in students.values():
print(x)
Output:
Mary
John
Peter

192.b
hllo.
The loop will skip the letter "e" and print out the rest.
193.c
Red, Green.
The loop will break once it finds blue in its path. It will not print
blue.
194.b
red, green
Since the print statement comes before the if statement, this code
will print red and green. If the print statement came after the break
statement, the code would print "red" only (see example 2).
Example 1 (print before the break statement)
colors = ["red", "green", "blue"]
for x in colors:
print(x)
if x == "green":
break
Output:
red
green

302 | Page
Example 2 (print after break statement)
colors = ["red", "green", "blue"]

for x in colors:
if x == "green":
break
print(x)
Output:
red

195.a
red, green, and blue.
Since the print statement has come before the if statement, this
code will print out all the items in the iteration. For the condition
to work, the print statement should come after the continue
statement.
colors = ["red", "green", "blue"]
for x in colors:
print(x)
if x == "green":
continue
Output:
red
green
blue

In the code below, we have moved the print statement after the
continue statement and the out has changed.
colors = ["red", "green", "blue"]
for x in colors:
if x == "green":
continue
print(x)
Output:
red
blue

303 | Page
196.d
2,10
Here is a simple way to understand the code:
The range starts from 2.
The range ends at 16.
The number 8 is how many numbers the code should skip after
printing 2. So after 2 it will print 10. After 10, it is supposed to
skip 8 numbers, but since our range ends at 16, the code will stop
at 10.

for x in range(2, 16, 8):


print(x)
Output:
2
10

197.a
2,6,10,14

for x in range(2, 16, 4):


print(x)
Output:
2
6
10
14

198.b
A loop within another loop.
When you have a loop inside a loop, it is a nested loop. Below is a
simple illustration of a nested loop. There is a loop inside a loop.
for a in b:
for b in c:
print(c)

304 | Page
199.
We use the zip() function to combine the two lists.
a = [1,2,3]
b = [ "yellow", "green", "red"]
for i, j in zip(a,b):
print(i,j)
Output:
1 yellow
2 green
3 red

200.a
You cannot use a for loop in a function.
You can easily combine a function with a for loop. Below is a
simple code that combines a function with a for loop.
b = [ "yellow", "green", "red"]

def colors(b):
for color in b:
print(color)
colors(b=b)
Output:
yellow
green
red

201.a
A for loop iterates over an iterable of known length,
while a while loop iterates over an iterable object as long
as the condition is True
A while loop iterates when a condition is true. A for loop iterates
over an iterable of a given length. With a while loop, the number
of iterations depends on a given condition evaluating to true.
202.b
Yes
This is because, in the given code, the condition will always be
true. The variable a will always be less than 10. As long as that
condition is true, the code will run forever. Try it, but be careful
it will crash your computer.

305 | Page
203.
Here is the code below:
a = 1
while a < 10:
print("This number is less than 10")
a += 2
Output:
This number is less than 10
This number is less than 10
This number is less than 10
This number is less than 10
This number is less than 10

204.a, b, d
The while loop will stop when a condition is false.
You can stop the while loop by using the break
statement.
A while loop will stop when the computer runs out of
memory.
Any of the above scenarios will stop a while loop.

205.c
0,1,2,4,5
The continue statement is simply telling the while loop that
once it finds 3 in the iteration, it should stop, skip 3 and
continue.
a = -1

while a < 5:
a += 1
if a == 3:
continue
print(a)
Output:
0
1
2
4
5

306 | Page
206.d
0,1,2
The while loop will break once it finds a 3. It will not print the 3.
a = -1

while a < 5:
a += 1
if a == 3:
break
print(a)
Output:
0
1
2

207.
Here is the loop below:
a = 1
while a < 5:
a += 1
print("This number is less than 5")
else:
print("End of the loop")
Output:
This number is less than 5
This number is less than 5
This number is less than 5
This number is less than 5
End of the loop

307 | Page
208.a
John is right, you can use a while loop to iterate through
the dictionary.
A while loop iterates while a certain condition is true. As long as
we can set that condition, we can use it to iterate through a
dictionary.
Below, we use a while loop to print out the values of a dictionary.
As long as a is less than the length of values in the dictionary, the
code will print out the values.
cars = {"name": "Ford", "year": 1992}

a = 0
while a < len(cars.values()):
key, value = cars.items()
print(value)
a +=1
Output:
('year', 1992)
('year', 1992)

209.
Yes, you can use a for loop inside a while loop. Here is a simple
example below.
cars = {"name": "Ford", "year": 1992}
a =1
while a < 10:
for items in cars.values():
print(items)
a += 5
Output:
Ford
1992

210.b
If statements can be used with while loops and for
loops.
Both while and for loops can incorporate conditional statements.

308 | Page
211.
a = 23
b = 45
def add(a, b):
sum1 = a + b
return sum1
print(add(23,45))
Output:
68

212.
a = 23
b = 45

def multiply(a, b):


c = a * b
return c
print(multiply(23,45))
Output:
1035

213.
a = 45
b = 66
c = 12

def multiply_and_divide(a,b,c):
d = (a * b)/c
return d
print(multiply_and_divide(23,45, 12))
Output:
86.25

214.
x = (10, 20, 21, 23, 24, 56, 78, 89)
y = min(x)
print(y)
Output:
10

309 | Page
215.
x = (10, 20, 21, 23, 24, 56, 78, 89)

for num in x:
if num == max(x):
print(num)
Output:
89

216.c
math.divide()
217.
You will have to import the math module.
import math

x = 64
def square_root(x):
y = math.sqrt(x)
return y
print(square_root (64))
Output:
8.0
218.b
math.isnan()
Math.isnan() checks whether a given item is a NaN (not a
number) or not. If it is a number, it will return false. Here is an
example below:
x = 3
print(math.isnan(x))
It returns False because x is a number.
Output:
False

219.
Using the abs() function, you can convert any number into an
absolute number.
a = -5.91
print(abs(a))
Output:
5.91

310 | Page
220.b
23
This method rounds down the number to the nearest integer.
Here is the code below:
z = math.floor(23.3)
print(z)
Output:
23
221.a
24
This method rounds up the number to the nearest integer.
Here is a code below:
a = math.ceil(23.4)
print(a)
Output:
24

222.a
368

p = max (12,13,16)
s = 23
print(p*s)
Output:
368

223.b
0
The modulus sign % gives the remainder of the division. When
you divide 16 by 8, there is no remainder.
224.
Using exponentiation, Mary can write the code in this way.
a = 2**5

Let’s check if these two expressions are equal.


a = 2 * 2* 2 * 2* 2
b = 2**5
# Checking if a is equal to b
print(a==b)
Output:
True

311 | Page
225.
8 is the remainder when you divide 89 by 9. Use the modulus
operator (%).
a = 89
b = 9

c = a % b
print(c)
Output:
8

226.
Using pow(), Mary can write the code below.
a = pow(5,4)
If we compare the two expressions, we get a True output, meaning
they are equal.
b = 5 * 5 * 5 * 5
a = pow(5,4)
print(b==a)
Output:
True

227.c
18
The trunc() method will remove the decimal point and return a
whole number.
228.d
5
In this code, we are simply returning 5 to the power of 3, and 8 is
a modulus (%). We can rewrite the expression as (5 * 5 * 5) % 8.
x = pow(5, 3, 8)
print(x)
Output:
5

312 | Page
229.a
6.238
We are multiplying pi by 2 in this expression.
230.d
1080
This code is simply multiplying the min of variable x, with the
max of variable y using the math method, math.prod().
231.b
input()
232.
my_name = input("Please enter your name:")
When you run this code, it will prompt the user to enter their
name.
233.
Here is the code below. Assuming the user inputs 45 for a and
30 for b, the output will be 75.
def add():
a = int(input("Enter a number:"))
b = int(input("Enter another number"))
c = a + b
return c
print(add())
Output:
75

234.
Here is the code below.
def multiply_divide():
a = int(input("Enter a number:"))
b = int(input("Enter another number"))
c = int(input("Enter another number"))
d = (a*b)/c
return d
print(multiplyAndDivide())
Output:
180.0

313 | Page
235.
def your_age(age):
age = input("Enter your age:")
print('Your age is ' + age + ' years old')
your_age(25)
Output:
Your age is 21 years old

236.b
A variable that can be accessed both locally and
globally.
A variable that can be accessed inside and outside of a function is
global.

237.b
Use the global keyword inside the function to declare c
a global variable.
By using the global keyword, you are making the variable
accessible to the local and global scope.
Janet should write the following code:
def my_Function():
global c
c = 200
return c

238.a
A variable that is declared inside a function and can
only be used in that function.
In the code below, c is a local variable because it can only be used
in this function.
def my_Function():
c = 200

314 | Page
239.a
True
By default, any variable declared outside of a function is global. It
can be used in a function and outside of a function. In the code
below, the variable num can be used within and outside the
function. This makes the variable num a global variable.

num = 12
def my_Function():
c = 200 + num
return c
print(my_Function())
Output:
212

240.b
False
When you declare a variable within a function, you do not need to
use the word "local" to make it a local variable. By default, a
variable declared within a function is a local variable.

241.b
False
To make a variable inside a function global, you have to declare it
global in the function.

242.b
try
The try block in code is used to handle errors in the code.

243.a
True
An error that is not handled will stop the program from running.

315 | Page
244.b
It handles the errors raised in the try block.
In the code below, the try block will raise a NameError since
"name" is not defined. However, the except block will handle this
error to prevent the program from crashing. We use the except
block to tell the program what to do with the errors in the
program.
try:
print(name)
except NameError:
print("name is not defined")
Output:
name is not defined

245.a
raise.
In the code below, using the keyword raise, we are telling the
code what kind of error to raise when x is less than 20. This will
let the user know if they enter any number below 20.
x = 10
if x < 20:
raise Exception ("no numbers below 20")
Output:
raise ValueError ("no numbers below 20")
ValueError: no numbers below 20

246.b
A code that runs after a try block whether an exception
is handled or not.
A finally block is the code that we want to run whether the error
has been handled or not. In the code below, we have handled the
error with the except block.

316 | Page
try:
print(name)
except NameError:
print("x is not defined")
finally:
print("End of code")
Output:
x is not defined
End of code

In the code below, we have not handled the error with the except
block, but even with the error, the finally block still prints out "End
of code." So, the finally block is the code that we want to
run, whether we have handled our errors or not.
try:
print(name)
finally:
print("End of code")
Output:
print(name)
NameError: name 'name' is not defined
End of code

247.
To prevent the error from ruining our program, we can use the try
and except blocks in the code.
try:
print(x)
except NameError:
print("x is not defined")
Output:
x is not defined

317 | Page
248.
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print(a / b)
except ZeroDivisionError:
print("You cannot divide a number by zero;try again")

Now that we have put the code in the try and except blocks, when
we try to divide a number by 0, it prints out "You cannot divide the
number by zero." This prevents the program from crashing.
Output:
You cannot divide a number by zero. Try again.

249.
Add the finally block after the except block.
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print(a / b)
except ZeroDivisionError:
print("You cannot divide a number by zero;try again")
finally:
print("End of code")

If a = 45 and b = 5, the output will be:


Output:
9.0
End of code

318 | Page
250.
Here is the modified code below.
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print(a / b)
except ZeroDivisionError:
print("You cannot divide a number by zero;"
"try again")
except ValueError:
print("You have not entered a valid number;"
" try again")
finally:
print("End of code")
251.
We have put everything into a function. We use the while loop to
ensure that the function only stops once it returns the answer.
def divide ():
while True:
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
return ("The answer is :" + str(a/b))
except ZeroDivisionError:
print("You cannot divide a number by zero;"
"try again")
except ValueError:
print("You have not entered a "
"valid number; try again")
finally:
print("End of code")

print(divide())

319 | Page
252.
Here is the code below:
def your_age():
while True:
age = int(input("Enter your age : "))
if age < 1:
print("You cannot enter a number "
"that is less than one;"
"try again")
elif age > 150:
print("You cannot enter a "
"number above 150;"
"try again")
else:
return 'Your age is:' + str(age) + \
' years old.'
print((your_age()))

253.b
A Python file that contains Python code.
254.b
Add .py at the end of the name.
Whatever name you give a module, just remember to add dot (.)
py at the end.
255.
Here is how to import the module add dot(.) py.
import add

256.c
A library is a collection of modules with different
functionalities, while a module is a file with different
functions.

When you combine different modules, you create a library.


257.c
A package manager in Python.
Pip is used to manage and install a lot of python libraries.

320 | Page
258.
Use "pip install pandas" in the cmd line. You should have pip
installed on your machine to successfully run this command. Pip
is installed together with Python (on windows).

For mac run "sudo pip install pandas".


259.
We are going to use the add() function from the add module.
import add

x = 23
y = 12
print(add.add(23,12))
Output:
35

260.b
from add import sum.
To import a function from a module, we start with the keyword
from.

261.c
import myfunction as mf.
262.a
dir()
Here is an example below. We will check the attributes and
methods of add.py ( the module we created in question 59).
import add

print(dir(add))
Output:
['__builtins__', '__cached__', '__doc__', '__file__',
'__loader__', '__name__', '__package__', '__spec__',
'add']

263.
from datetime import time, date, datetime

321 | Page
264.
from datetime import datetime

x = datetime.now().strftime("%H:%M:%S")
print(x)
The time when I ran the code was:
Output:
21:43:42

265.
from datetime import datetime

x = datetime.now().strftime("%m/%d/%Y")
print(x)
Output:
09/10/2021
266.
This time we print out the time.
from datetime import datetime

x = datetime.today().strftime("%H:%M")
print(x)
Output:
10:42

267.
from datetime import date

x = date.today()
print(x)
Output:
2022-07-31

268.b
strftime()
This method allows us to format our time. We have used it in
previous questions.

322 | Page
269.b
2021
When you pass the argument "%G" to the strftime() method,
the output is a year.
270.a
Thursday
When you pass the argument ‘%A’ to the strftime() method,
the output is a day of the week.
271.
def age():
a = input("Enter your year of birth:")
b = datetime.today().strftime("%Y")
your_age = int(b) - int(a)
return "You are " + str(your_age) + " years old."
print(age())

If the user enters 1966 as their year of birth, below will be the
output (remember to import the datetime module from datetime).
Output:
You are 55 years old.

272.c
An anonymous function or a function without a name.
While a normal function requires a name, a lambda function
has no name.
273.a
It can only take a limited number of arguments.
A lambda expression can take an unlimited number of
arguments, but it can only have one expression.

323 | Page
274.b
432
This lambda expression has three arguments: a, b, and c.
However, it has one expression. The expression is what comes
after the ":". In this expression, we are simply multiplying the
three arguments by 2.
v = lambda a,b,c: a*b*c*2
print(v(12,3,6))
Output:
432
275.
Remember that a lambda function can only have one expression.
x = lambda a,b:(a+b)*2
print(x(10,15))
Output:
50

276.d
6
v = lambda a:a/2
print(int(v(12)))
Output:
6

277.c
0
This expression simply finds the remainder of the division (using
the modulus % operator). In this case, the division of 12 by 2 gives
no remainder. That’s why the answer is 0.
v = lambda a:a%2
print(int(v(12)))
Output:
0

324 | Page
278.b
4.0
We are dividing 20 by 5 in this function.
def divide(num):
return lambda y : y / num

divide1 = divide(5)
print(divide1(20))
Output:
4.0

279.
def divide(num):
return lambda y: y / num

divide1 = divide(5)
print(divide1(50))
Output:
10.0
280.
results = [ 32, 45, 78, 67, 88, 97, 76, 84,
44, 66, 63, 86, 90, 80]

# Using list, filter, and lambda


marks = list(filter(lambda x: (x > 60),results))
print(len(marks))

We can see from the output that 11 people got over 60 marks.
Output
11

325 | Page
281.
results = [ 32, 45, 78, 67, 88, 97, 76, 84,
44, 66, 63, 86, 90, 80]

# Using list, filter, and lambda


marks = list (filter (lambda x: (x < 50), results))
print(len(marks))

We can see from the output that 3 people got less than 50 marks.
Output:
3

282.b
It is structured into objects of similar properties and
behaviors.
Everything in Python is some kind of object. An object with its
properties and methods. The class keyword is used to create
objects in Python.
283.b
It means to create a blueprint for creating objects
A class is a blueprint for creating objects in object-oriented
programming (OOP).
284.
An instance of a class is simply an object that belongs to that class.
Let’s create a class called "Animals." Remember, a class is like a
box or a container that holds objects. The objects that we will add
are a dog, a cat, and a fish. Since a dog belongs to the animal class,
we can say it is an instance of the animal class. A cat is an instance
of the animal class. A fish is an instance of the animal class
(meaning a fish belongs to and uses attributes from the animal
class).

326 | Page
class Animals:
def __init__(self, name, age):
self.name = name
self.age = age

# Creating instances of class


cat = Animals("cat", 3)
dog = Animals("dog", 4)
fish = Animals("fish", 1)
285.a
class Car:
When giving your class a name, the name should always start with
an uppercase letter.
286.d
print(Cat.i)

287.c
To assign values to class instances.
When you create a class, the constructor will be used to assign
object parameters or instance attributes.
288.a
class Car:
def __init__(self,brand, model):

289.d
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model

290.
class Car:
def __init__(self,brand, model):
self.brand = brand
self.model = model

car1 = Car('Nissan','Murano')
print(car1.model)
Output:
Murano

327 | Page
291.
class Car:
def __init__(self,brand, model):
self.brand = brand
self.model = model

car1 = Car('Nissan','Morano')
car2 = Car('Ford','Focus')
print(car2.brand)
Output:
Ford

292.
class Car:
def __init__(self,brand, model):
self.brand = brand
self.model = model

car1 = Car('Nissan','Morano')
car2 = Car('Ford','Focus')

# assign new values to the car2 object


car2.brand= "Honda"
car2.model= "Civic"
print(car2.brand)
Output:
Honda

328 | Page
293.
class Car:
def __init__(self,brand, model):
self.brand = brand
self.model = model

car1 = Car('Nissan','Morano')
car2 = Car('Ford','Focus')

# assign new values to the car2 object


car2.brand= "Honda"
car2.model= "Civic"

# deleting Car class


del Car
print(Car)

When we run the code, we get an error because "Car" has been
deleted and no longer exists.
Output:
print(car2)
NameError: name 'Car' is not defined. Did you mean: 'car1'?

294.b
John
You can put a function inside a class. The function is a method of
the class. Three types of methods can be added to a class—instance
method, class method, and static method. Here is an example of a
class with an instance method. We assign the self parameter to link
the function to the instances (objects). Here is a class below:

329 | Page
class Car:
def __init__(self,brand, model):
self.brand = brand
self.model = model

# instance method
def car_print(self):
print( "My favorite car is : " + self.brand)

car1 = Car('Nissan','Morano')
print(car1.car_print())
Output:
My favorite car is: Nissan

295.b
It is called when an object gets destroyed.
Simply put, when you delete a class object (object goes out of
scope), the destructor __del__() is called to remove the garbage.
The garbage, in this case, is the deleted object and all the resources
that it was using. These resources are freed up.
296.b
When one class inherits the methods and properties of
another class.
In the code below, there are two classes: the parent class and the
child class. The child class inherits methods and properties from the
parent class.
# parent class
class Animals:
def __init__(self, name, color)

# child class
class Dog(Animals):
pass

330 | Page
297.b
Super()
In the example below, the Dog class is inheriting properties and
methods from the Animals class by using the super() method.
class Dog(Animals):
def __init__(self, name, color)
super().__init__(name,color)

298.
In the code below, we have created a second object for the Father
class.
class Father:
def __init__(self, firstname,lastname, age):
self.firstname = firstname
self.lastname = lastname
self.age = age

def print_father(self):
print("Your first name is {} "
"and your last name is {}. "
"You are {} years old".format(self.firstname,
self.lastname, self.age))

# creating the first object


father1 = Father("Richard", "Kelly", 42)
# creating the second object
father2 = Father("Benson", "Carter", 52)

print(father2.print_father())
Output:
Your first name is Benson and your last name is Carter. You
are 52 years old

299.a
class Son(Father):

When creating a child class, we put the name of the parent class
inside the parenthesis.

331 | Page
300.
class Father:
def __init__(self,firstname,lastname,age):
self.firstname = firstname
self.lastname = lastname
self.age = age

# instance method
def print_father(self):
return f"First name: {self.firstname}, last name: " \
f"{self.lastname}, Age: {self.age}."

# creating a child class


class Son(Father):
pass

# creating an object for the child class


son1 = Son("Shawn", "Kelly", 21)
# printing the son1 using the print_father function
print(son1.print_father())
Output:
First name: Shawn, last name: Kelly, Age: 21.

332 | Page
301. We use the super() function in the child class to access the
properties and methods of the parent class.
class Father:
def __init__(self,firstname,lastname,age):
self.firstname = firstname
self.lastname = lastname
self.age = age

# instance method
def print_father(self):
return f"First name: {self.firstname}," \
f"last name: {self.lastname}, Age:
{self.age}."

class Son(Father):
def __init__(self, firstname, lastname, age, height):
# using super function to inherit properties from parent
super().__init__(firstname, lastname, age)
self.height = height

# instance method
def print_son(self):
return f" First name: {self.firstname}," \
f"last name: {self.lastname}," \
f"Age: {self.age}, Height {self.height}."

# creating the son1 object


son1 = Son('Shawn', 'Kelly', 21, "5'9")
# print the son one using the print son function
print(son1.print_son())
Output:
First name: Shawn,last name: Kelly,Age: 21, Height 5'9.

302.c
open()
303.
We can open the file using the open() method. The open method
takes two arguments: the name of the file we want to open and
the mode. The mode is the state we want to open the file in. In
our case, we want to open the file so we can read it. So, the mode
is "r" for read.
with open('names.txt', 'r') as x:
print(x.read())

333 | Page
304.
To create a file, we use the open() method. We have to use a
different mode called "x". This will create a file. We use the write
() method to write "Elephant" onto the file.
with open('animals.txt', 'x') as x:
x.write("Elephant")

We can also use the mode "w", and if that file does not exist, it
will create one. See below.
with open('animals.txt', 'w') as x:
x.write("Elephant")

305.
To add another line to the file, we can use the open() method
and the append mode, "a". See below:

with open('animals.txt', 'a') as x:


# Using escape characters to write in separate lines
x.writelines(["\nLion","\nTiger"])
Let’s check below if the information has been appended correctly
to the file. We can open the file in read mode.

with open("animals.txt", 'r') as x :


print(x.read())
Output:
Elephant
Lion
Tiger

334 | Page
306.a
It will overwrite an existing file.
If there is an existing file name and you use the "w" mode, it will
get overwritten.

307.
Below is a code you can use to create and write to the file. If
you are using the with statement, you do not need to use the
close statement at the end of your code. The with statement
will close the file for you.
with open('my_first_file.txt', 'w') as x:
x.write("This is my first line")

To read the file we just created, we can use the code below.
with open('my_first_file.txt', 'r') as x:
print(x.read())
Output:
This is my first file

308.
Here is the code to append a line to the file. Remember to change
the mode to "a" for append.
with open('my_first_file.txt', 'a') as x:
x.write('\nThis is my last line')

Let’s open the file now.


with open('my_first_file.txt', 'r') as x:
print(x.read())
You can see from the output below that a line has been added to
our file.
Output:
This is my first line
This is my last line

335 | Page
309.
To delete a file, you have to import the os module. The module
will first check if the file exists, and then it will remove it.
import os

os.path.exists("my_first_file.txt")
os.remove("my_first_file.txt")

310.
Any number that does not return a remainder of zero(0) when
divided by two (2) is an odd number.
arr = [1, 2, 4, 6, 7, 9, 11, 17, 23, 26, 27]

# Create an empty list to append odd numbers


odd_numbers = []
for number in a:
if number % 2 != 0:
odd_numbers.append(number)
print(odd_numbers)
Output:
[1, 7, 9, 11, 17, 23, 27]

311.
Any number that returns a remainder of zero (0) when divided by
two (2) is an even number. We use the modulus operator (%) for
this operation.
arr = [1, 2, 4, 6, 7, 9, 11, 17, 23, 26, 27]

# we create an empty list to append even numbers


even_numbers =[]
for number in arr:
if number % 2 == 0:
even_numbers.append(number)

print(even_numbers)
Output:
[2, 4, 6, 26]

336 | Page
312.
Duplicate numbers are numbers that appear more than once in
the list. We use the count method to count the occurrences of
each number in the list. If a number appears more than once,
we add it to the duplicates list.
arr = [1, 1, 3, 5, 6, 1, 3, 6, 7, 8, 9, 6, 8, 9]

duplicates = []
for number in arr:
if arr.count(number) > 1:
if number not in duplicates:
duplicates.append(number)

print(duplicates)
Output:
[1, 3, 6, 8, 9]

313.
def convert_to_min():
while True:
try:
hrs = input("Enter the number of hours:")
minutes = int(hrs) * 60
except ValueError:
print('Please enter a valid number')
else:
print("The number of minutes is:" + str(minutes))
break

convert_to_min()

337 | Page
314.
Here is a simple calculator code below. The errors raised in the try
block (value error and zero division error) will be handled in the
except blocks.
def calc():
while True:
try:
a = int(input("Enter a number"))
b = input("Enter an operator")
c = int(input("Enter another number"))
if b == '+':
add = a + c
return add
elif b == "-":
subtract = a - c
return subtract
elif b == "*":
multiply = a * c
return multiply
elif b == "/":
division = a/c
return division
except ValueError:
print('Please enter a valid number')
except ZeroDivisionError:
print('Zero division error. Try again')

print(calc())

338 | Page
315.
Here is the code below. Import the module random to generate
random numbers. Use the while loop to ensure the code keeps
running until the user guesses the correct number.
import random

a = random.randint(0,10)

def guess_num():
while True:
guess = int(input("Guess a number between 0 and 10 :"))
if guess > a:
print('Your number is too high.')
elif guess < a:
print("Your number is too low.")
else:
print("Correct. You have won.")
break

guess_num()

316.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12]

total = 0
for num in a:
total = total + num
print(total)
Output:
78

317.
str = 'This Is noT how wE writE A sentence'

con1 = []
for letter in str:
if (letter.isupper()) == True:
con1.append(letter)
print(len(con1))
Output:
6

339 | Page
318.
We use the sum() function to add the numbers in the dictionary.
Can you refactor the code below by putting it into a function? That’s
another challenge for you.

a = {"Men": 20,"women": 25}


b = {"children": 23,"students": 44}

c = a.values()
d = sum(c)
e = b.values()
f = sum(e)
total = d + f
print(total)
Output:
112

319.
def smallest_odd(a: list):
odd = []
for num in a:
# if number has no remainder when divided by 2
if num % 2 != 0:
odd.append(num)
return min(odd)

list1 = [17, 23, 13, 24, 25, 33, 71, 81, 30]

print(smallest_odd(list1))
Output:
13

320.
def center(a):
# find length of str
length = len(a)
# find middle element
middle = length//2
# If length is odd number
if len(a)%2==1:
return a[middle]
else:
return "No middle character"

print(center("welcome"))
Output:
C

340 | Page
321.
Remember that there are different ways to solve this challenge.
This is just one of them. Below, we use the all() function. The all()
function will return true if all the items in the list are the same.
names = ['Peter', 'Peter', 'Peter', 'Peter']

def all_same(a):
same = all(item == a[0] for item in a)
if (same):
return 'The names are the same'
else:
return 'The names are not the same.'
print(all_same(names))

Passing the argument "names" into the function, we get the


following outcome.
Output:
The names are the same.

341 | Page
Other Books by Author
1. 50 Days of Python: A Challenge a Day

Imagine mastering Python fundamentals by completing one challenge or


two a day. Well, you don't have to imagine that there are challenges that
will help you master the fundamentals of the Python language as you begin
your journey to build and create great things with Python. Even if you are
extremely busy, you can set aside some time each day to complete one
challenge, and by the end of 50 days, you will have mastered the Python
fundamentals.

2. Python Tips and Tricks : A Collection of 100 Basic & Intermediate Tips & Tricks.

342 | Page
Index
A F
Allowed Variable Names, 17 FIFO and Lists, 43
Appending Files, 152 Filter Function, 105
Arithmetic Operators, 65 Finally Statement, 130, 132
Flask Module, 160
B for loop, 115
format strings, 29
Boolean Data Types, 26 Frozen Sets, 53
Break Statement, 118, 124
G
C
Greater Than Operator, 69
class attributes, 137
Class Attributes, 135
H
Class Methods, 138
Classes, 135 Help Function, 163
Closing Files, 153
Comments in Python, 13 I
Comparison Operators, 68
Conditional Statements Flowchart, 110 Identity Operators, 72
Continue Statement, 118, 125 Illegal Variable, 18
create a module, 157 import modules, 158
Creating Decorators, 97 Indentation in Python, 14
Creating Files, 151 Inheritance, 144
Creating Functions, 85 input from users, 82
Creating Sets, 47 instance attributes, 138
Instance Attributes, 136
Iterating Through a Range, 117
D
DateTime Module, 169 L
Decorator as a Timer, 100
default arguments, 87 lambda, 104
Deleting Class Objects, 143 len() function, 31
Deleting Files, 154 Less Than Operator, 69
Dictionary Keys, 55 LIFO and Lists, 42
Dictionary Keys and Values, 55 List Comprehension, 120
Dictionary Methods, 58 List Functions, 38
docstring, 13 List Properties, 35
Lists, 34
Lists Methods, 39
E
Local and Global Scope, 93
Elif Statement, 108 logical error, 128
Else Statement, 109, 121, 125, 130 Logical Operators, 71, 111
Encapsulation, 146
Exponent Operator, 66 M
Map Function, 105
math functions, 76

343 | Page
Math Module, 77 simple password checker, 126
math operations on lists, 37 Static methods, 140
Membership Operators, 70 String Escape Methods, 29
multiple variables, 16 String methods, 31
Multiplication Operator, 66 Strings, 27
Subtraction Operator, 66
N syntax error, 128

Nested Dictionaries, 61
T
Nested For Loops, 119
Nested If-Statements, 111 The Division Operator, 67
None Data Type, 26 The Floor Division Operator, 67
Numeric Data Types, 24 The Modulus Operator, 68
Time Functions, 168
P Time Module, 166
timeit() Module, 169
Pandas Module, 161 Try and Except, 128
Pass Statement, 86 tuple methods, 46
Polymorphism, 145 Tuples, 45
Pure Functions, 101 Type Hints, 92
Python Dictionary, 54 Typecasting, 61
Python Pip, 158
Python Reserved Keywords, 19
U
Python Variables, 14
Unpacking *Operator, 72
Q Unpacking a Dictionary using **Operator,
73
Quotation Marks, 14
V
R
Variable Names, 17
Random Module, 159
Reading Files, 152
W
Reassigning Variables, 16
Reduce Function, 106 while loop, 124
Return Statement, 87 with Statement, 153
Returning Multiple Values, 88 Writing Files, 151

S Y
Self in Classes, 141 Yield Statement, 89
Set Properties, 48
Sets, 47 Z
Sets Methods, 50
Shorthand Syntax, 112 Zen of Python, 163

344 | Page
345 | Page

You might also like