Practice Python Questions and Challenges For Beginners
Practice Python Questions and Challenges For Beginners
Python
Questions and Challenges
For Beginners.
Benjamin Bennett Alexander
"Python" and the Python Logo are trademarks of the Python Software
Foundation.
1|Page
Copyright © 2021 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
I welcome and appreciate your feedback and reviews. Please leave
reviews on the platform you purchased this book from. Please send
your feedback and queries to: benjaminbennettalexander@gmail.com
3|Page
Table of Contents
Feedback ........................................................................................ 3
Table of Contents .......................................................................... 4
About this Book ............................................................................. 6
Downloading Python and IDE ..................................................... 8
Syntax and Variables .................................................................. 10
Data Types and Typecasting ...................................................... 17
Python Tuples .............................................................................. 22
Lists in Python ............................................................................. 26
Python Sets................................................................................... 31
Operators in Python.................................................................... 33
Strings and Boolean Values ........................................................ 37
Python Dictionary ....................................................................... 41
Functions in Python .................................................................... 46
Conditional Statements............................................................... 52
For Loop ....................................................................................... 54
While Loops ................................................................................. 60
Python Math ................................................................................ 63
User Input .................................................................................... 68
Python Variable Scope................................................................ 69
Error Handling ............................................................................ 71
Pip and Modules .......................................................................... 74
Dates in Python............................................................................ 77
4|Page
Lambda ........................................................................................ 79
Python Classes ............................................................................. 82
File handling ................................................................................ 88
Extra Challenges ......................................................................... 90
Answers ........................................................................................ 94
What is Next? ............................................................................ 216
Acknowledgement ..................................................................... 217
About Author............................................................................. 218
5|Page
About this Book
This book has over 300 questions and challenges that will test your
Python language knowledge as a beginner. It has both multiple-choice
and open-ended questions. Learning to program is not just about
reading books, but it’s about practicing and writing code. Problem-
solving is one of the most effective ways to learn a programming
language. Whether you are new to Python or programming in general,
or you just want to brush up on your Python skills, this book has
enough questions and challenges to help you kickstart your Python
career. Practice Python is about asking you questions and challenging
you to find the answers. Answers, explanations, and example codes
are provided for all the questions and challenges. You are also at
liberty to go online and dig deeper into the various topics that we cover
in this book.
In this book, we cover everything that you need to know as a Python
beginner. Once you master these Python basics, you will have the
skills and knowledge to go on to learn and build great things with
Python. So, what are some of the things that will cover in this book?
• Variables and Syntax. Understanding the proper way to create
variables and the set of rules for writing proper Python syntax
is important for every beginner.
• We will cover Python data structures – lists, tuples, sets, and
dictionaries.
• We will explore strings and various ways we can manipulate
them using string methods.
• We will cover Python operators and Python math.
• Learning to organize code into functions is one of the most
important skills that help programmers write clean code. Every
Python beginner will become comfortable with functions after
tackling questions and challenges in this book.
• We will explore conditional statements – If, elif, and else
statements.
6|Page
• Programming is about handling errors. We will explore how
errors are handled in Python.
• We shall tackle modules and libraries in Python
• Python is an object-oriented programing language, so every
beginner should know about classes and inheritance.
• We will also cover dates, lambda functions and so much
more.
We will cover a lot of stuff that every Python beginner should know.
If you can answer and solve the challenges in this book, then you have
mastered the basics of Python and you are on your way to writing more
complex Python code.
7|Page
Downloading Python and IDE
You will need to have Python 3 installed on your machine to run the
codes in this book successfully. If you do not have Python installed on
your machine, you can download it here:
https://www.python.org/downloads/
Make sure that you download the latest version of python.
To write and execute code you will need a code editor or an Integrated
Development Environment (IDE) to be installed on your machine.
There are many code editors and IDEs out there that you can use. I
recommend any of the following:
1. Pycharm
Download the community version from the link below:
https://www.jetbrains.com/pycharm/download/#section=wi
ndows
2. Jupyter notebook
Use the link below to find out how you can install the Jupyter
notebook on your machine.
https://jupyter.org/install.html
3. IDLE Shell
IDLE comes pre-installed with python for windows and
mac, so you will not need to download it separately. When
you click to open python, you will open the IDLE shell to
write and execute code. Pretty easy to use for beginners.
4. Sublime
You can download sublime text from the link below:
https://www.sublimetext.com/download
8|Page
5. Atom
https://atom.en.uptodown.com/windows
You can explore any of these and settle for the one that you are
comfortable with.
9|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
3.You cannot start a Python variable with a capital letter. True or False
a. True
b. False
10 | P a g e
5.John is trying to create a variable name for a value called orange.
Which one of the following codes will return an error?
a. fruit = "Orange"
b. Fruit = "Orange"
c. _fruit = "orange"
d. -fruit- = "Orange"
11 | P a g e
9.Mike writes down the following code:
9Myname = "Mike"
Mike runs the code and it generates a syntax error. What is wrong
with the code?
a. The name Mike should not be in quotation marks
b. The name Mike should not start with a capital letter
c. The variable name should not start with a number
d. Myname should not be written as one word
12 | P a g e
12.Which one of the following cannot be used as a variable name?
a. False
b. Name2
c. Cars
d. Car
13 | P a g e
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
14 | P a g e
18.John writes the following code:
a, b, c = "alphabet", "banana", "car"
Which one of the following codes will print “car”?
a. print(a)
b. print(b)
c. print(c)
d. print(:2)
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
15 | P a g e
21.What is the difference between a statement and an expression in
Python?
a. A statement is a line of code that does something while an
expression is a line of code that evaluates into something
b. An expression is a line of code that does something while
a statement is a line of code that evaluates into something
c. A statement is a line of code that combines something
while an expression is a line of code that divides something
d. A statement is a line of code that runs all the time while an
expression is a line of code that runs when called
16 | P a g e
Data Types and Typecasting
23.Which of the following is a data type in Python? Select all that
apply.
a. variable
b. float
c. integer
d. complex
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
18 | P a g e
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
19 | P a g e
33.Which one of the following best explains typecasting?
a. Converting one data type into another using a Python
function
b. Typecasting is printing out Python data
c. Converting numerical type data into a string
d. Writing clean code in Python
37.Convert the following code into a float using typecasting. Print out
the data type of your new variable.
x = 23
20 | P a g e
38.John wants to convert a variable y which is an integer into a string.
How does he convert an int variable into a string using typecasting?
a. y = string(y)
b. y = str(y)
c. y =float(y)
d. y = int(y)
21 | P a g e
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, 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).
22 | P a g e
48.Which one of the following is true about tuples?
a. No duplicates are allowed in a tuple
b. You cannot create a tuple of Boolean data types
c. You cannot have a tuple with different data types
d. There is no limit to the number of items you can add to a
tuple
49.There are two ways to create a tuple, using round brackets () and
using a tuple constructor. Create a tuple of colors – Red, Blue, 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
52.You can use the sort() method to sort a tuple in ascending order only.
True or False?
a. True
b. False
23 | P a g e
53.Can you have duplicate items in a tuple?
a. No, you cannot have duplicates in a tuple
b. Yes, you can have duplicates in a tuple
55.John wants to change the last item in the tuple (question 54).
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]
24 | P a g e
57.Jane has written down the following codes:
animals = ("dog", "cat", "duck", "chicken")
fruits = ("oranges", "apples", "mangoes", "bananas")
Write a code to combine the two tuples.
25 | P a g e
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
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 code to sort your list. Print
out the sorted list.
65.A sort() method sorts a list only in ascending order. True or False?
a. True
b. False
26 | P a g e
66.Which one of the following is not a list method?
a. sort()
b. copy()
c. return()
d. pop()
27 | P a g e
70.Janet writes down the following code:
a = [1,2,4,4,5,6,7,8,9]
Janet wants to remove 4,4,5 from the list. Help Janet with a code
that will remove these numbers. Print out the updated list.
28 | P a g e
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()
29 | P a g e
77.
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"
30 | P a g e
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 of three items called a 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.
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.
31 | P a g e
87.Write a code to clear all the elements of the following set. Print out
the results.
v = {12, 90, 89, 23, 56}
88.Create a set of numbers 1-10 using the set() constructor. The variable
name of the set should be num. Print out the num class type.
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"}
32 | P a g e
Operators in Python
94. Which one of the following operators is used to add values
together?
a. *
b. +
c. –
d. %
95.
x = 2**3
print(x)
What answer do we get when we run the code?
a. 6
b. 8
c. 12
d. 16
96.
y=6*3
print(y*2)
What is the result of this expression?
a. 11
b. 12
c. 36
d. 40
33 | P a g e
97.Which one of the following is a division operator in Python?
a. //
b. /
c. %
d. \\
98.
x = 6//4
print(x*2)
What is the result of this code?
a. 6
b. 3
c. 4
d. 2
99.
x = 6/4
print(x*2)
What do you get when you run this code?
a. 1.5
b. 2.0
c. 3.0
d. 4.0
34 | P a g e
101.Which one of the following is the same as c = c + 5?
a. c =+ 5
b. c += 5
c. c - = 5
d. c = - 5
35 | P a g e
105. What is the shorthand for y = y // 5?
a. y = y/5
b. y /=5
c. y //=5
d. y =//
36 | P a g e
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
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
37 | P a g e
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])
111.
y = "I am learning Python"
Write a code to replace ‘learning’ with ‘studying’ in the variable y.
38 | P a g e
114. Which of the following string methods will capitalize the first
character in a string?
a. capitalize()
b. upper()
c. casefold()
d. capital()
116. Which one of the following string methods converts the whole
string into an upper case?
a. upper()
b. capitalize()
c. casefold()
d. capital()
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
40 | P a g e
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]
125.Write a code to access the keys and values of the car's dictionary
(question 124). Use a for loop.
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
41 | P a g e
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).
132.Alison changed his mind and decides to delete the dictionary. Write
a code that will delete the dictionary.
42 | P a g e
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.
136.Here is a dictionary:
mydict = {"name": "Mary", "occupation": "Singer"}
Write a code to create a copy of this dict.
a. newdict = mydict.copy
b. newdict = mydict.copy()
c. newdict = mydict.copy[]
d. newdict = copy(mydict)
43 | P a g e
138.Which one of the following is not a dict method?
a. popitem()
b. delete()
c. pop()
d. setdefault()
44 | P a g e
143.What is the difference between a dictionary and a tuple?
a. Dictionary is mutable while a tuple is immutable
b. Dictionary is immutable while a tuple is mutable
c. Dictionary is ordered, while a tuple is not ordered
d. There is no difference between a dictionary and a tuple
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).
45 | P a g e
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
46 | P a g e
152.John wants to create a function named car with the parameter called
carname. Which one of the following is a valid function?
a. def_car (carname):
b. def car (carname):
c. def car ("carname"):
d. Def car("carname"):
47 | P a g e
157.Write a function called MultiplyAndDivide with three parameters
a, b and c. The function multiplies the two parameters a and b and
divides it by c. Create a local variable for the function (variable
name = results). Pass 12, 24, 8 as arguments of the function. Your
function should return 36.0. Print the results.
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 argument of the function
c. Write a function without arguments
d. She must know the actual number of arguments before
writing the function
48 | P a g e
161.Is there a limit to the number of parameters that a function can
take?
a. A function cannot take over 10 parameters
b. A function cannot take over 5 parameters
c. A function cannot take over 2 parameters
d. There is no limit to the number of parameters a function
can take
49 | P a g e
164.Jane writes the following function:
def my_fun()
sum1 = 11 + 11
return sum1
print(my_fun())
This function generates an error. What is wrong with this function?
a. There is nothing wrong with the function
b. : is missing at the end of the function name
c. The function should not be indented
d. sum is a reserved word in a function
50 | P a g e
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. Now 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
51 | P a g e
Conditional Statements
171.Create a function called max_num with one parameter, a. If a is less
than 10, it should print ‘The number is less than 10’. Else it should
print ‘The number is not less than 10’. Pass the number 12 as an
argument for the function.
if a != b:
print("it’s not equal")
The code generates an error. What is wrong with the code?
a. The if statement should be in a function
b. The print statement is not indented
c. “it’s not equal” should not be in inverted commas
d. The print statement should not be in round brackets
52 | P a g e
175.Mikel writes the following code:
a = 22
b =34
Write an if statement that prints out “B is superior to A” if b is greater
than a. Otherwise print out “A is superior to B” if a is greater than b.
179.Write the following into code. Put everything in one line (shorthand
syntax). If a is greater than b or a is greater c, print out “Life is
good”.
53 | P a g e
For Loop
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
54 | P a g e
186.Which one of the following is a reserved keyword used in a for loop
to stop and continue the iteration?
a. break
b. continue
c. proceed
d. next
55 | P a g e
190.What is the result of running the following code?
for x in range(10):
if x == 5:
continue
print(x)
a. 1,2,3,4,5,6,7,8,9,10
b. 0,1,2,3,4,5,6,7,8,9,10
c. 0,1,2,3,4,6,7,8,9,10
d. 0,1,2,3,4,6,7,8,9
56 | P a g e
193.What is the result of running the following code?
colors = ["Red", "Green", "Blue"]
for x in colors:
if x == "Blue":
break
print(x)
a. Green
b. Green, blue
c. Red, Green
d. Red, Green, Blue
57 | P a g e
195.Which of the following is the result of running the code below?
colors = ["red", "green", "blue"]
for x in colors:
print(x)
if x == "green":
continue
a. red, green, blue
b. green, blue
c. red, green
d. red, blue, green
58 | P a g e
198.What is a nested for loop?
a. A big loop
b. A loop within another loop
c. A small loop
d. None of the above
59 | P a g e
While Loops
201. What is the difference between a while loop and a for loop?
a. A for loop iterates through a given number of items or
range of objects, while a while loop iterates through
items or objects as long as the condition is true
b. A while loop iterates through a given number of items or
range of objects, while a for loop iterates through items
or objects 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
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. (a = 1). Remember to
increment the variable a by 2 for every iteration.
204.How can you stop the 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
60 | P a g e
205.Ben writes the following loop:
a = -1
while a < 5:
a += 1
if a == 3:
continue
print(a)
Which of the following is the output of this code?
a. 1,2,3,4,5,6
b. 0,1,2,3,4,5
c. 0,1,2,4,5,
d. 0,1,2,3,4,5,6,7
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”. Remember to increment a. (a =1).
61 | P a g e
208.John wants to use a while loop to iterate through the dictionary.
Peter said 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
62 | P a g e
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.
215.Using a for loop and if statement, write a code that finds the max of
x (question 213). Print out the answer.
63 | P a g e
217.Write a function that finds the square root of the variable below.
Print out the answer.
x = 64 (Use a math method.Import math)
64 | P a g e
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
65 | P a g e
227. What is the result of the following code?
a = math.trunc(18.9)
print(a)
a. 12
b. 13
c. 18
d. 19
66 | P a g e
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
67 | P a g e
User Input
231.Which one of the following methods 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 enter their name. The variable of
the code should be my_name.
233.Write a function called adds that adds two variables a and b. The
code should request the user to input a and b. Remember to convert
the user input into 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.
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”.
68 | P a g e
Python Variable Scope
236.What is a global variable?
a. A variable inside a function that can only be accessed in
a function
b. A variable that can be accessed within the local and
global scope
c. A variable that can be changed
d. A variable that is created within a function
69 | P a g e
239.Any variable declared outside a function is a global variable. True
or False?
a. True
b. False
70 | P a g e
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
71 | P a g e
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
249.Add a finally block to your code (question 248). The finally block
should print “End of code”.
72 | P a g e
250.Modify your code (question 249), so that it also can handle
‘ValueError’. If someone enters something that is not a number,
print ‘You have not entered a valid number. Try again ’.
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. Use a while loop inside the function to ensure that the
function runs until it returns the results of the expression (the
division of a/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
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. Use the variable name – age, for inputs from users. If a
person enters a number less than 1, the code should print ‘You
cannot enter a number that is less than 1. Please try again ’. If
someone enters a number that is above 150, the code should say
‘You cannot enter a number above 150. Please try again ’. If
someone enters a valid age, it should print “Your age is: + age +
years old”. Hint: Use a loop and conditional statement to handle the
error.
73 | P a g e
Pip and Modules
253.What is a module in Python?
a. A function and statement in Python
b. A Python file that contains Python code
c. A Python library
d. Any Python code is a module
255.Mary has created a function file named add.py. She wants to use
this function in a new file. Write a code to import this module into
her new file.
74 | P a g e
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.
75 | P a g e
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()
76 | P a g e
Dates in Python
263.Write a code to import time, date, and datetime from the datetime
module.
264.Using the datetime module, write a code that prints out your current
time (Hour: Minutes: Seconds as format). (Use the now() function
and its format attribute). Create a variable called x for your time.
265.Using datetime module and now() function and its format attribute,
print today’s date, just date. Create a variable called x for the date.
Print date in this format - month: date: year.
267.Using the date module and the today() function, create a variable x
and print the current date.
77 | P a g e
269. This is Jack’s code:
import datetime
y = datetime.datetime(2021, 7, 1)
print(y.strftime("%G"))
What is the result of running this code by Jack?
a. July
b. 2021
c. 1
d. 2020
271. Challenge. Write a function called age that calculates a user’s age.
The function should ask the user to enter their year of birth and it
should return their age. The function should print ‘You are:’ +
user’s age +. ‘years old.’
78 | P a g e
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
79 | P a g e
276. What is the result of running this code?
v = lambda a:a/2
print(int(v(12)))
a. 6.0
b. 12
c. 0
d. 6
divide1 = divide(5)
print(divide1(20))
What is the result of this code?
a. 0.25
b. 4.0
c. 5
d. 6
279. Modify the code (question 278). Change the value of y to 50 and
run the code. What is the new output?
80 | P a g e
280. Here is a list of exam results of students at a certain school:
results = [ 32, 45, 78, 67, 88, 97, 76, 84, 44, 66, 63, 86, 90, 80]
John wants the list filtered so he can know how many students got
over 60 marks. Using the filter() function and lambda function,
write a code that will show John how many students got over 60
marks.
281.Write another code for John (question 280) that will show how
many students got less than 50 marks.
81 | P a g e
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
285. What is the correct syntax for creating a class called car?
a. class Car:
b. (class car):
c. class car():
d. class_car:
82 | P a g e
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)
83 | P a g e
289.Which of the following is the correct way to assign values to class
objects?
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.
84 | P a g e
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.
85 | P a g e
297. Which one of the following functions are used to by the child class
to inherit from the parent class?
a. __init__()
b. super()
c. def()
d. self()
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
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())
Create the second object - father2. The first name is Benson, the Last
name is Carter and the age is 52. Print out father2.
86 | P a g e
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):
300. Add a child class to the code (question 298). The name of the child
class is Son. The child class inherits properties from the Father
class. Create the child class and do not add any content to it (pass).
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 to print out son1.
301. Modify your code (question 300) by adding properties to the child
class (Son class). Use the __init__() function, to assign ‘height’ to
the Son class. Ensure that the Son class still inherits properties and
methods from the Father class. Create a new method for the Son
class called print_son (similar to print_father in the Father class).
The print_son function should print what is printed by the
print_father method but you should add “and your height is” at the
end. Modify the son1 object you just created (question 299) (First
name: Shawn, Last name: Kelly, Age: 21, height 5’9). Use the
print_son method to print this out.
87 | P a g e
File handling
302.Which one of the following keywords are used to open text files
in Python?
a. append()
b. read()
c. open()
d. extend()
303.You have a text file called names. 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. Write a code to create
the file using the open() method and the with statement. Add an
animal called Elephant to your file.
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. 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.Using the with statement, write a code to create a text file called
my_first_file. Write ‘This is my first file’ on to the file. Then write
another code to open and read your file.
88 | P a g e
308.Write a 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.
309.Write a code to delete the file you have created (question 308).
Import os for this operation.
89 | P a g e
Extra Challenges
310.Write a code that finds and prints out odd numbers in the variable
a.
a = [1, 2, 4, 6, 7, 9, 11, 17, 23, 26, 27]
311.Write a code that finds and prints out even numbers from the list.
a = [1, 2, 4, 6, 7, 9, 11, 17, 23, 26, 27]
312.Write a code that finds duplicates in the following list.
a = [1, 1, 3, 5, 6, 1, 3, 6, 7, 8, 9, 6, 8, 9,]
Print out the duplicates.
313.Write a function called convert that converts hours to minutes. The
function should ask the user for input. The function should return
the number of hours converted into minutes. Ensure that the code
does not crash when a user inputs something that is not a number.
90 | P a g e
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]
317. Write a code that finds how many capital letters are in the string
below. Print out the 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}
91 | P a g e
321.Jane has written the following code:
names = ['Peter', 'Peter', 'Peter', "Peter"]
Jane wants to write a code that will be able to check if all the names
in the list are the same. If the names are the same, the code should
return, ‘All the names in the list are the same ’. If they are different,
the code should return ‘The names in the list are not the same ’.
Write a code for Jane.
92 | P a g e
Answers
93 | P a g e
Answers
1.a
It’s a set of rules on how a Python code will be written and
interpreted.
2.a
A reserved memory location for an object.
When you create a variable, you are reserving some space where
the object you have created can be saved. You assign it a point of
reference, which is the variable name. To access or use the object
you have to call the variable. In the code below to use 2, we need
to call on the variable x.
x=2
3.b
False
You can start a variable name with either an upper letter or a lower
letter.
4.c
myname
94 | P a g e
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 ( - ).
6.b
False
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
9.c
The variable name should not start with a number.
95 | P a g e
10.c
The name Peter should have been put in quotation marks.
The object should have been put in quotation marks to tell Python
that it is a string. That’s a proper syntax. The only thing that does
not need quotation marks is digits and variable names.
11.c, e
My-name
My name
12.a
False
96 | P a g e
13.List is not one of the reserved words in Python. However, it is a built-
in function. As good practice, you are not to use reserved words and
built-in function names as variables. If John uses the word as a
variable, the code will run but the reference to the built-in function
will not work.
14.a
del
97 | P a g e
15.b
print is a built-in function in Python so it should not be used.
print = 67
print(print)
The code generates an error because the print function cannot work
anymore. It has been ‘overwritten’ by the print variable.
Output:
TypeError: 'int' object is not callable
16.a
Variable names are case-sensitive so fruit is not equal to Fruit.
To print fruit, Kelly needs to use the small-letter fruit in the code.
17.c and d
Fruit = Mango
Fruit = int(Mango)
C and d are not strings. If you check the class type of c and d it
will not be a string.
98 | P a g e
18.c
print(c)
19.b
#This is a comment
'''
20.a, b
car = "Toyota"
car = 'Toyota'
99 | P a g e
21.a
A statement is a line of code that does something while an
expression is a line of code that evaluates to something.
100 | P a g e
22.c
‘firstname’ + ‘lastname’
Remember an expression always evaluates into something. And,
when you print out an expression it will give results.
'firstname' + 'lastname'
print('firstname'+ 'lastname')
Output:
firstnamelastname
23.b, c, d
float
integer
complex
Float – 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 – 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 numbers and
imaginary numbers.
24.a
20
101 | P a g e
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
apples = {"apples", "mangoes", "Oranges"}
print(type(apples))
Output:
<class 'set'>
102 | P a g e
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
103 | P a g e
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 function int().
y = 1.5
y = int(y)
print(type(y))
When we print the type y, we can see from the output that the
float has been converted into an integer class using the function
int().
output:
<class 'int'>
34.a
5.0
104 | P a g e
35.
The code below converts x into an integer using the int function
is:
x = "10"
x = int(x)
print(type(x))
Output:
<class 'int'>
36.
Using the function str() we can convert an integer into a string
x = 10
x = str(x)
print(type(x))
Output:
<class 'str'>
37.
The code to convert an int to float using the float() function is:
x = 23
x = float(x)
print(type(x))
Output:
<class 'float'>
38.b
y = str(y)
105 | P a g e
39.b
4
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'>
106 | P a g e
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
107 | P a g e
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 it 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')
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.
108 | P a g e
Using the count() function we can check the number of times the
name “Jane” appears in our tuple – names. We can see from the
output that Jane only appears once. We are passing the name ‘Jane’
as the argument.
print(names.count("Jane"))
Output:
1
47.c
index()
We can see from the output the position of “Alice” in our tuple.
Remember that Indices start at 0. In the tuple – names, “Jane” is
position 0, which means ‘Alice’ is position 2.
Output:
2
109 | P a g e
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
110 | P a g e
51.a
x is a tuple, y is a set
52.False
You cannot use a 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)
We can now convert the list back to a tuple using the tuple()
function.
# Converting a list to a tuple
num2 = tuple(num2)
print(num2)
Output
(1, 2, 5, 8, 9, 45, 78)
111 | P a g e
53.b
Yes, you can have duplicates in the tuple.
54.a
print(len(animals))
55.d
Tuples are immutable
If you want to update a tuple, you will have to create a new one.
You 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.
112 | P a g e
57.
We can combine the two tuples using the + operator and create a
new tuple.
animals = ("dog", "cat", "duck", "chicken")
fruits = ("oranges", "apples", "mangoes", "bananas")
animals_and_fruits = animals + fruits
print(animals_and_fruits)
Output:
('dog', 'cat', 'duck', 'chicken', 'oranges', 'apples', 'mangoes',
'bananas')
58.
We can use multiplication to double the contents of a tuple. We can
create a new tuple. Multiply our tuple by 2.
cars = ("BMW", "Isuzu", "Nissan")
cars2 = cars*2
print(cars2)
Output:
('BMW', 'Isuzu', 'Nissan', 'BMW', 'Isuzu', 'Nissan')
59.c
count()
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.
113 | P a g e
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]
63.
numbers = [10, 20, 40, 70, 60, 90, 100, 55, 78, 89]
114 | P a g e
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]
115 | P a g e
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. You can set the
sorting criteria for the method. Below is a code sorting a list in
descending order using the sort() method.
numbers = [10, 20, 40, 70, 60, 90, 100, 55, 78,89]
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']
116 | P a g e
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.
68.d
print(cars[3])
69.c
It is immutable
Lists are not immutable. You can delete, change, add and sort items
in a list. Lists are ordered.
117 | P a g e
70.
Using the del method and indexing we can remove the items from
the list.
a = [1,2,4,4,5,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.
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
118 | P a g e
74.b
append()
print(girls_names)
Output:
['Mary', 'Rose', 'Kate', 'Amanda', 'Jane']
119 | P a g e
75.b
append adds a single item to the list, while extend increases
the list by the number of iterable items.
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 a list by one
item - the other list.
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 b list 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]]
120 | P a g e
76.b
BMW and Toyota
77.d
cars[-4]= "Benz"
78.a
0
79.b
sorted()
121 | P a g e
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.
122 | P a g e
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}
85.
Using 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()
123 | P a g e
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()
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((1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
print(type(num))
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
124 | P a g e
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.
125 | P a g e
91.
Let’s use examples to demonstrate the difference between the two
methods.
Update() method
Update method updates the original set with the content of the
new set. See the example below.
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.
126 | P a g e
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.
95.b
8
127 | P a g e
96.c
36
97.b
/
128 | P a g e
98.d
2
99.c
3.0
This is a division sign /. When you divide 6 / 4 you get 1.5. Multiply
1.5 by 2, you get 3.0. Remember that a / sign will always return a
floating number that is why we are getting a 3.0.
x = 6/4
print(x*2)
Output:
3.0
129 | P a g e
100.b
//operator returns the result without decimal places, while /
operator returns the results with decimal places.
101.b
c += 5
130 | P a g e
102.b
0
103.d
equal
104.a
True
105.c
Y //=5
131 | P a g e
106.b
A sequence of characters surrounded by quotation marks
132 | P a g e
108.d
y=5
109.c
print(y[5: 13])
133 | P a g e
110.a
print(y[-6:])
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
134 | P a g e
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
114.a
capitalize()
135 | P a g e
115.a
lower()
Example below:
y = "Ben"
print(y.lower())
Output:
ben
116.a
upper()
The code below demonstrates how the upper() method converts the
whole string to the upper case.
y = "i love ben"
print(y.upper())
Output:
I LOVE BEN
117.b
len()
136 | P a g e
118.c
\n
119.b
True
120.a
True
137 | P a g e
121.b
True
122.a
student = {"name": "John", "age": 23}
A dictionary has curly brackets and it has a key and a value. In the
dictionary above “name” is a key and “John” is a value.
123.a
Immutable
138 | P a g e
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}
139 | P a g e
127.d
Keys cannot be changed
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()
140 | P a g e
131.
You can remove a key from a dictionary using the pop() method.
Pass the key that you want to remove as an argument.
Output:
{'names': 'Nissan'}
132.
Alison can use the keyword del() to delete the dictionary. You can
see below that trying to print cars after running del generates an
error because the dictionary cars do not exist.
cars = {"names": "Nissan", "year": 2007}
del cars
print(cars)
Output:
NameError: name 'cars' is not defined
141 | P a g e
133.
We are going to create a dictionary called students, that will be
nested. When we run print students, you can see that we get a
dictionary with dictionaries in it. This is a nested dictionary.
Student1 = {"name": "John", "grade" : "F"}
Student2 ={ "name" : "Alison", "grade" : "B"}
Student3 = {"name" : "Ben", "grade" : "C"}
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'}}
142 | P a g e
135.d
clear()
Clear() will remove contents from the dictionary. Let’s use our
previous question example to demonstrate this. When we try to
print the dictionary after running clear(), we get an empty
dictionary.
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'}
143 | P a g e
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()
139.b
Dictionaries allow duplicate values.
140.b
Items in a dict are accessed by keys while items in a list are
accessed by referencing their position.
144 | P a g e
141.
x = { "name": "carol", "age": 23, "school": "Yale"}
print(x['school'])
Output:
Yale
142.b
They are both mutable.
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 | P a g e
145.
x = { "name": "carol", "age": 23, "school": "Yale"}
for items in x.keys():
print(items)
Output:
name
age
school
146.
The expression ‘name in x’ will return a Boolean value. 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
c=a|b
print(c)
Output:
{'name': 'John', 'Grade': 11, 'school': 'yale', 'location': 'USA'}
146 | P a g e
148.b
A block of code that performs a specific task and runs when
called.
149.b
def
Every function block in Python will start with the keyword def.
150.b
def my_car():
151.a
Values that are passed into a function when it is called.
Arguments are passed into the brackets 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
for 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
147 | P a g e
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 any arguments it will use the default
argument.
In the code below, when we call the function, in the first code we
pass “Honda” as an argument, and the code prints out Honda. In the
second one, we do not pass any argument, and the function prints
out BMW, which is our default argument.
155.a
To tell the function to return the results of the function.
148 | P a g e
156.d
All the above.
157.
Here is the code below:
def MultiplyAndDivide(a,b,c):
results = a*b/c
return results
print(MultiplyAndDivide(12,24,8))
Output:
36.0
158.c
A function can accept zero parameters.
149 | P a g e
159.b
She’s right we can use different arguments for one function.
def MultiplyAndDivide(a,b,c):
results = a*b/c
return results
print(MultiplyAndDivide(12,24,8))
Example 2
def MultiplyAndDivide(a,b,c):
results = a*b/c
return results
print(MultiplyAndDivide(16,14,6))
150 | P a g e
160.b
Pass *args as the argument 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. When you use *args as an argument, Python will store the
input into a tuple.
def myFunc(*args):
return "His cars are " + str(args).strip('()')
print(myFunc("BMW","Honda","Benz"))
Output:
His cars are 'BMW ', 'Honda ', 'Benz '
161.d
There is no limit to the number of parameters a function can
take.
151 | P a g e
162.b
The sub1 and return should have been indented.
152 | P a g e
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
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
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
153 | P a g e
164.b
: is missing at the end of the function name.
def my_fun():
x=1
166.c
print(subtract(10,5))
154 | P a g e
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 is simply telling
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
155 | P a g e
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
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.
if a != b:
print("it’s not equal")
Output:
it’s not equal
156 | P a g e
173.b
elif statement
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
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
157 | P a g e
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
178.
In this conditional statement, we are using the or operator.
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
158 | P a g e
179.
if a > b or a > c: print("Life is good")
180.b
or
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
159 | P a g e
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
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’.
186.b
160 | P a g e
continue
187.b
To stop the current iteration and begin a new one.
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"]
161 | P a g e
189.d
0,1,2,3,4
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
192.b
hllo
The loop will skip the letter ‘e’ and print out the rest.
162 | P a g e
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 has come 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.
Example 1
colors = ["red", "green", "blue"]
for x in colors:
print(x)
if x == "green":
break
Output:
red
green
Example 2
colors = ["red", "green", "blue"]
for x in colors:
if x == "green":
break
print(x)
Output:
red
163 | P a g e
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.
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
164 | P a g e
196.d
2,10
197.a
2,6,10,14
165 | P a g e
198.b
A loop within another loop.
199.
Here is the code below:
a = [ "yellow", "green", "red"]
b = [1,2,3,4]
for colors in a:
for numbers in b:
print(colors,numbers)
Output:
yellow 1
yellow 2
yellow 3
yellow 4
green 1
green 2
green 3
green 4
red 1
red 2
red 3
red 4
166 | P a g e
200.a
You cannot use a for loop in a function.
def colors(b):
for color in b:
print(color)
colors(b=b)
Output:
yellow
green
red
201.a
A for loop iterates through a given number of items or range of
objects, while a while loop iterates through items or objects as
long as the condition is 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.
167 | P a g e
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
168 | P a g e
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
169 | P a g e
206.d
0,1,2
The while loop will break once the iteration 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
170 | P a g e
208.a
John is right, you can use a while loop to iterate through the
dictionary.
a=2
while a < 3:
x = cars.items()
print(x)
a += 1
Output:
dict_items([('name', 'Ford'), ('year', 1992)])
171 | P a g e
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.
211.
a = 23
b = 45
def add(a, b):
sum1 = a + b
return sum1
print(add(23,45))
Output:
68
172 | P a g e
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
173 | P a g e
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
174 | P a g e
218.b
math.isnan()
219.
Using the abs() function, you can convert any number into an
absolute number.
a = -5.91
print(abs(a))
Output:
5.91
220.b
23
175 | P a g e
221.a
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.
176 | P a g e
224.
Using exponentiation, Mary can write the code in this way.
a = 2**5
We can even check if these expressions are equal, with the code
below.
a = 2 * 2* 2 * 2* 2
b = 2**5
print(a==b)
Output:
True
225.
8 is the remainder when you divide 89 by 9.
a = 89
b=9
c=a%b
print(c)
Output:
8
177 | P a g e
226.
Using pow(), Mary can write the code below.
a = pow(5,4)
If we compare the two expressions, we get a True statement,
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
229.a
6.238
178 | P a g e
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.
def add():
a = int(input("Enter a number:"))
b = int(input("Enter another number"))
c=a+b
return c
print(add())
Output:
75
179 | P a g e
234.
Here is the code below.
def multiplyAndDivide():
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
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 within the local and global
scope.
180 | P a g e
237.b
Use the global keyword within the function to declare c a
global variable.
By using the global keyword, you are making variable c accessible
within the local and global scope.
Janet should write the following code:
def my_Function():
global c
c = 200
238.a
A variable that is declared inside a function and can only be
used in that function.
num = 12
def my_Function():
c = 200 + num
return c
print(my_Function())
Output:
212
181 | P a g e
240.b
False
241.b
False
242.b
try
243.a
True
An error that is not handled will stop the program from running.
182 | P a g e
244.b
It handles the error 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 ValueError ("no numbers below 20")
Output:
raise ValueError ("no numbers below 20")
ValueError: no numbers below 20
183 | P a g e
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.
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
184 | P a g e
247.
To prevent the error from ruining our program, we can use the try
and except keywords in the code.
try:
print(x)
except NameError:
print("x is not defined")
Output:
x is not defined
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")
185 | P a g e
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")
finally:
print("End of code")
186 | P a g e
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 in 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."
"Please try again")
except ValueError:
print("You have not entered a "
"valid number. Please try again")
finally:
print("End of code")
print(divide())
187 | P a g e
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."
"Please try again")
elif age > 150:
print("You cannot enter a "
"number above 150."
" Please 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.
255.
Here is how to import the module add.py
import add
188 | P a g e
256.c
A library is a collection of files with different functionalities,
while a module is a file with single functionality & statement.
257.c
A package manager in Python.
258.
In windows type ‘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.
259.
We are going to use the add method from the add module.
import add
x = 23
y = 12
print(add.add(23,12))
Output:
35
189 | P a g e
260.b
from add import sum.
262.a
dir()
263.
from datetime import time, date, datetime
264.
from datetime import datetime
x = datetime.now().strftime("%H:%M:%S")
print(x)
190 | P a g e
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:
2021-07-31
268.b
strftime()
191 | P a g e
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 datetime module from datetime).
Output:
You are 55 years old.
272.c
An anonymous function or a function without a name.
192 | P a g e
273.a
It can only take a limited number of arguments.
274.b
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
193 | P a g e
277.c
0
278.b
4.0
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
194 | P a g e
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
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.
195 | P a g e
283.b
It means to create an object.
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 and uses attributes from the animal class).
285.a
class Car:
When giving your class a name, the name should always start with
an upper letter.
286.d
print(Cat.i)
287.c
To assign values to class members.
196 | P a g e
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
197 | P a g e
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')
Output:
Honda
198 | P a g e
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 car2 has been
deleted and no longer exists.
Output:
print(car2)
NameError: name 'car2' is not defined
199 | P a g e
294.b
John
class Car:
def __init__(self,brand, model):
self.brand = brand
self.model = model
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 using del(), the
destructor __del__() is called to remove the garbage. The garbage
in this case is the deleted object.
200 | P a g e
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 (Dog class) is inheriting methods and
properties of the parent class (Animals class).
# parent class
class Animals:
def __init__(self, name, color)
# child class
class Dog(Animals):
pass
297.b
Super()
201 | P a g e
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 in
the brackets. We basically pass the parent class as an argument.
202 | P a g e
300.
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))
Output:
Your first name is Shawn and your last name is Kelly. You
are 21 years old.
203 | P a g e
301.
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,))
class Son(Father):
def __init__(self, firstname, lastname, age, height):
# using the name of the parent to inherit its properties
Father.__init__(self, firstname, lastname, age)
self.height = height
def print_son(self):
print("Your first name is {} and your last name is {} "
"you are {} years old and your height is {} ."
format(self.firstname, self.lastname,self.age,self.height))
Output:
Your first name is Shawn and your last name is Kelly you are
21 years old and your height is 5'9.
204 | P a g e
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.
304.
To create a file we use the open() method. We have to use a
different mode called x. This will create a file and add an Elephant
to it.
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")
205 | P a g e
305.
To add another line to the file, we can use the open() method and
the append ‘a’ mode.
with open('animals.txt', 'a') as x:
# Using escape characters to write in separate lines
x.writelines(["\nLion","\nTiger"])
Output:
Elephant
Lion
Tiger
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.
206 | P a g e
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 code for you.
with open('my_first_file.txt', 'w') as x:
x.write("This is my first file")
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 below 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')
Output:
This is my first file
This is my last line
207 | P a g e
309.
To delete a file, you have to import a file os module. The module
will first check if the file exists and then it will delete it or remove
it.
import os
os.path.exists("my_first_file.txt")
os.remove("my_first_file.txt")
310.
Here is the code below:
a = [1, 2, 4, 6, 7, 9, 11, 17, 23, 26, 27]
Output:
[1, 7, 9, 11, 17, 23, 27]
208 | P a g e
311.
a = [1, 2, 4, 6, 7, 9, 11, 17, 23, 26, 27]
# we create an empty list to append even numbers
even_numbers =[]
for number in a:
if number % 2 == 0:
even_numbers.append(number)
print(even_numbers)
Output:
[2, 4, 6, 26]
312.
c = [1, 1, 3, 5, 6, 1, 3, 6, 7, 8, 9, 6, 8, 9,]
duplicates = []
for number in c:
if c.count(number) > 1:
if number not in duplicates:
duplicates.append(number)
print(duplicates)
Output:
[1, 3, 6, 8, 9]
209 | P a g e
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()
210 | P a g e
314.
Here is a simple calculator code below.
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('You cannot divide a number by zero. Try again')
print(calc())
211 | P a g e
315.
Here is the code below:
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
212 | P a g e
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
318.
We use the sum() function to add the numbers in the dictionary.
a = {"Men": 20,"women": 25}
b = {"children": 23,"students": 44}
c = a.values()
d = sum(c)
e = b.values()
f = sum(e)
total = d + f
print(total)
Output:
112
213 | P a g e
319.
a = [17, 23, 13, 24, 25, 33, 71, 81, 30]
odd = []
for num in a:
if num % 2 != 0:
odd.append(num)
print(min(odd))
Output:
13
320.
def center(a):
length = len(a)
middle = length//2
if len(a)%2==1:
return a[middle]
else:
return "No middle character"
print(center("welcome"))
Output:
C
214 | P a g e
321.
Remember that they are different ways to solve this challenge.
This is just one of them.
names = ['Peter', 'Peter', 'Peter', "Peter"]
def all_same(a):
same = all(item == a[0] for item in a)
if (same):
return 'The names are the same'
else:
return 'The names are not the same.'
print(all_same(names))
Passing the argument ‘names’ into the function, we get the
following outcome.
Output:
The names are the same.
215 | P a g e
What is Next?
Once you have mastered the basics of Python language, you are
ready to tackle advanced uses of the Python language. Where do
you go from here? What things can you do with your Python
knowledge? Python is a general-purpose programming language
that can be used in a variety of areas in programming.
Web Development
Popular web development frameworks such as Django and Flask
are written in Python. Once you master the basics of Python you
can start learning these frameworks to learn about web applications.
Gaming
Python is widely used in the gaming industry. If you are interested
in game development, you can explore popular gaming frameworks
such as Pygame and many more to create games.
Data Science and Analysis
Python is the number one language used in data science and
machine learning and data analytics and visualizations. Some of the
most popular data science libraries such as NumPy, Pandas,
TensorFlow, Scikit-Learn, Pytorch, Matplotlib, and many more are
written in python. Once you master the basics of Python, you can
start exploring these libraries if you have an interest in data science.
Automation and Scripting
Python is also widely used in scripting to automate tasks that
require repetition like sending emails and downloading files.
These are some of the areas you can explore once you master the
basics of Python. Remember, there is so much to learn about Python
and it all starts with mastering the basics. Practice Python.
216 | P a g e
Acknowledgment
Massive thanks to Andrew for the great cover design and other
invaluable contributions to the writing of the book.
217 | P a g e
About Author
The author is a student of life, a father, a husband, a finance and
programming enthusiast. For queries, comments, and suggestions,
you can reach him at: benjaminbennettalexander@gmail.com
218 | P a g e
219 | P a g e
220 | P a g e