Professional Documents
Culture Documents
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
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
4.Python Math............................................................ 76
Built-in Math Functions ................................................................................. 76
The Math Module ........................................................................................... 77
Chapter Summary .......................................................................................... 80
Challenges ...................................................................................................... 80
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
6 | Page
Chapter Summary ......................................................................................... 126
Challenges ..................................................................................................... 126
7 | Page
The Zen of Python ......................................................................................... 163
The Help Function ........................................................................................ 163
Chapter Summary ......................................................................................... 164
Challenges ..................................................................................................... 164
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():
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'}
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.
_name = 'John'
print(_name)
Output:
John
17 | Page
We can use numbers in a variable name as long as the number is not the
first character of the variable name.
name9 = 'John'
print(name9)
Output:
John
Example 2
first-name = 'John'
print(first-name)
Output:
first-name = 'John'
^
SyntaxError: cannot assign to operator
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
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
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
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?
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.
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'>
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
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
b = "Am learning"
c = '''Am learning
Python'''
print(type(a))
print(type(b))
print(type(c))
Output:
<class 'str'>
<class 'str'>
<class 'str'>
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
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
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.
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:
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.
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
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
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
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
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]
[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']
●
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]]
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
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()
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]
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]
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']
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
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
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.
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
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
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'}
48 | Page
num_set ={12, 78, 19, 0, 78, 67, 55}
print(num_set)
Output:
{0, 67, 19, 55, 12, 78}
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.
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'
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'}
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'}
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'
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
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.
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'}
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).
59 | Page
dict1 = {"name": "Mary",
"school": "Yale",
"age": 22}
print(dict1.get('name'))
Output:
Mary
60 | Page
dict1 = {"name": "Mary",
"school": "Yale",
"age": 22}
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"
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.
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]
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
x = 8
y = 3
# using the division operator
b = x / y
print('The answer of division is ', b)
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
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
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
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
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 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
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
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']
# 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.
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.
In the above code, the sum() function goes over the list and adds up all
the values.
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.
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
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 = (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.
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
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')
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
Note that the pass statement is not exclusive to functions. It can be used
in other areas of Python code.
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.
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
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
89 | Page
def func():
for i in range(4):
return i
num = func()
print(num)
print(num)
print(num)
Output:
0
0
0
num = func()
print(next(num))
print(next(num))
print(next(num))
Output:
0
1
2
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
91 | Page
def myFunc(**kwargs):
for key, value in kwargs.items():
print(f'{key} = {value}')
print('\n')
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
print(my_func())
Output:
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
def my_func():
global my_number
my_number = my_number + 5
return my_number
print(my_func())
Output:
28
94 | Page
def func():
print('This is a function')
upper_or_not()
95 | Page
def sort_names(x):
return x[0]
print(sorted_names)
Output:
[('Chris', 'Rock'), ('John', 'Kelly'), ('Will', 'Smith')]
# Second function
def func2(n):
return n*2
# Third function
def run(func, n):
return func(n)
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")
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
print(used_inside_decorator())
Output:
I run inside the inner function of decorator.
Decorated function executed.
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
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.
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:
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
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.
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.
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
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:
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
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."
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
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
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]
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]
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.
We can also do the same for the values of a dictionary. See an example
below.
dict1 = {"Name": "Mary","School": "Yale","age": 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
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.
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
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.')
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.
2. Write a code that prints out all the numbers in the list except 8 and
9:
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."
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
124 | Page
The while loop stops after printing one "Valid" because of the break
statement.
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.
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')
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}')
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.
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"
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'
136 | Page
class Animals:
# class attribute
home = 'zoo'
def __init__(self, name, age):
# creating instance attribute
self.name = name
self.age = age
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'
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.
138 | Page
class Animals:
# class attribute
home = 'zoo'
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'
# 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}'
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'
# 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:
# 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
def display(self):
return self.name
print(Animal.display())
Output:
TypeError: Animal.display() missing 1 required positional
argument: 'self'
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'
# 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.")
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
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:
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.
# instance methods
def run(self):
return f'Please run {self.brand}'
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
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()
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"]
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.
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)
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/
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)]
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:
161 | Page
import pandas as pd
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
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
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.
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.
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.
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
You can see now that our time is now more readable. The asctime
method returns a 24-character string.
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
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
today = datetime.date.today()
print('Today is', today)
Output:
Today is 2022-01-23
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
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
duplicates = []
for number in list1:
if list1.count(number) > 1:
if number not in duplicates:
duplicates.append(number)
print(duplicates)
Output:
[10, 30, 60]
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)
175 | Page
Chapter 4
1. We use the max() and min() functions for this challenge. Here is the
code below:
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)
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.
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.
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.
178 | Page
Chapter 9
1. Here is the code below:
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]
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
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"]
# Reading file
with open('names.txt', 'r') as file:
print(file.read())
Output:
John
Mary
John
Peter
Salah
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']
import pandas as pd
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.
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
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
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
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"
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
190 | Page
22. Which one of the following is an expression?
a. while loop
b. print(name)
c. 'firstname' + 'lastname'
d. if statement
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
What data type do you get when you run this code?
a. Set
b. bool
c. dict
d. float
What data type do you get when you run this code?
a. dict
b. tuple
c. list
d. let
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)
35. Using typecasting, write a code that converts the following code
into an integer.
x = "10"
37. Convert the following code into a float using typecasting. Print out
the data type of your new variable.
x = 23
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()
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
196 | Page
52. You can use the sort() method to sort a tuple in ascending order
only. True or False?
a. True
b. False
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")
58. Jane wants to double the code elements in the following tuple:
cars = ("BMW", "Isuzu", "Nissan")
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.
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.
print(cars.count("Toyota"))
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])
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.
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"]
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"
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).
91. What is the difference between the update() method and the
union() method?
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
205 | Page
99. What is the result of running this code.
x = 6/4
print(x*2)
206 | Page
102. John has written down the following code:
b = 12%3
print(b)
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.
114. Which of the following string methods will capitalize the first
character of a string?
a. capitalize()
b. upper()
c. casefold()
d. capital()
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()
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))
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]
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).
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()
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
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).
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():
153. Create a function called add that takes two parameters, number1
and number2. Return the sum of the two numbers.
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
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
218 | Page
164. Jane writes the following function:
def my_fun()
sum1 = 11 + 11
return sum1
print(my_fun())
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
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")
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
221 | Page
176. Which one of the following reserved keywords is used in
conditional statements?
a. and
b. more
c. greater
d. than
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."
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
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
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.
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
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)
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
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
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
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)
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?
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.
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
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
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.
a. 240
b. 9.6
c. 3.75
d. 5
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
235 | Page
239. Any variable declared outside a function is 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)
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."
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
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.
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
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))
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
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
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))
print(father1.print_father())
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.
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]
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}
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.
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)
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)
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))
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'>
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
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)
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")
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)
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]
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"))
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)
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.
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']
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}
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.
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.
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.
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
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"]
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"]
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.
197.a
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
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
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")
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.
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).
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]
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]
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
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')
328 | Page
293.
class Car:
def __init__(self,brand, model):
self.brand = brand
self.model = model
car1 = Car('Nissan','Morano')
car2 = Car('Ford','Focus')
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))
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}."
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}."
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:
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')
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]
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]
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.
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))
341 | Page
Other Books by Author
1. 50 Days of Python: A Challenge a Day
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