Python Interview Book
Python Interview Book
74 Python Deque.....................................................................87
75 Python ChainMap............................................................. 88
76 Progress Bar with Python................................................. 89
To fully benefit, please try your best to write the code down and
run it. It is important that you try to understand how the code
works. Modify and improve the code. Do not be afraid to
experiment.
By the end of it all, I hope that the tips and tricks will help you
level up your Python skills and knowledge.
Output:
13 6 7
Method 1
Method 2
Let’s say we want to see April 2022; we will use the month class
of the calendar module and pass the year and month as
arguments. See below:
import calendar
month = calendar.month(2022 , 4)
pri nt(month)
Output:
April 2022
MoTuWeThFr Sa Su
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 1617
18 19 20 21 22 23 24
25 26 27 28 29 30
There are so many other things you can do with the calendar.
For example, you can use it to check if a given year is a leap
year or not. Let’s check if 2022 is a leap year.
import calendar
month = calendar.isieap(2022)
pri nt(month)
Output:
Fal se
4 | Get Current Time and Date
The below code demonstrates how you can get the current time
using the datetimeQ module. The strftimeQ method formats
time for the desired output. This code breaks down how you can
use the datetime module with the strftimeQ method to get a
formatted string of time in hours, minutes, and seconds format.
from datetime import datetime
time_now = datetime.now().strftime('%H:%M:%S')
print(f'The time now is {time_now}')
Output:
The time now is 17:53:19
What if we want to return today’s date? We can use the date class
from the datetime module. We use the todayQ method. See
below:
from datetime import date
today_date = date.today()
pri nt(today_date)
Output:
2022-07-21
5 | Sort a List in Descending Order
The sort() method will sort a list in ascending order (by default).
For the sort method to work, the list should have the same type
of objects. You cannot sort a list mixed with different data types,
such as integers and strings. The sort() method has a parameter
called reverse; to sort a list in descending order, set reverse to
True.
listl = [2, 5, 6, 8, 1, 8, 9, 11]
1istl.sort(reverse=True)
pri nt(listl)
Output:
[11, 9, 8, 8, 6, 5, 2, 1]
The sort() method does not return a new list; it sorts an existing
list. If you try to create a new object using the sort() method, it
will return None. See below:
listl = [2, 5, 6, 8, 1, 8, 9, 11]
list2 = listl.sort(reverse=True)
pri nt(li st2)
Output:
None
6 Swapping Variables
In Python, you can swap variables once they have been assigned
to objects. Below, we initially assign 20 to x and 30 to y, but then
we swap them: x becomes 30 and y becomes 20.
x, y = 20, 30
x, y = y, x
print('x is' , x)
print('y is' , y)
Output:
x is 30
y is 20
# step one
X A= y
# step two
y a= x
# step three
X A= y
count_peter = Counter(1istl).get("Peter")
newlist = []
for list2 in listl:
for j in list2:
newli st.append(j)
pri nt(newli st)
Output:
[1, 2, 3, 4, 5, 6]
Using itertools
import itertools
flat_list = list(itertools.chain.from_itecable(listl)))
pri nt(flat_li st)
Output:
[1, 2, 3, 4, 5, 6]
In the code below, the max() function takes the list and the
lambda function as arguments. We add the enumerate^
function to the list so it can return both the number in the list
and its index (a tuple). We set the count in the enumerate
function to start at position zero (o). The lambda function tells
the function to return a tuple pair of the maximum number and
its index.
You can also use the abs() function on a floating number, and
it will return the absolute value. See below:
a = -23.12
pri nt(abs(a))
Output:
23.12
Using startswith()
listl = ['lemon','Orange',
'apple', 'apricot']
Using endswithQ
listl = ['lemon','Orange',
'apple', 'apricot']
This is cool, but slicing does not make code readable. There is a
Python built-in module that you can use that will make your life
easier. It is called heapq. With this module, we can easily return
the 5 largest numbers using the nlargest method. The method
takes two arguments: the iterable object and the number of
numbers we want to return. Below, we pass 5, because we want
to return the five largest numbers from the list.
Using nlargest
import heapq
results = [12, 34, 67, 98, 90, 68, 55, 54, 64, 35]
print(heapq.nlargest(5, results))
Output:
[98, 90, 68, 67, 64]
Using nsmallest
Import headq
results = [12, 34, 67, 98, 90, 68, 55, 54, 64, 35]
print(headq.nsmal1est(5, results))
Output:
[12, 34, 35, 54, 55]
Ml Checking for Anagram
You have two strings; how would you go about checking if they
are anagrams?
If you want to check if two strings are anagrams, you can use
counterQ from the collections module. The counterQ supports
equality tests. We can basically use it to check if the given
objects are equal. In the code below, we are checking if a and b
are anagrams.
from collections import Counter
a = 'lost'
b = 'stol'
pri nt(Counter(a)==Counter(b))
Output:
T rue
if sorted(a)== sorted(b):
pri nt('Anagrams')
else:
print("Not anagrams")
Output:
Anagrams
15 I Checking Internet Speed
Did you know that you can check internet speed with Python?
There is a module called speedtest that you can use to check the
speed of your internet. You will have to install it with pip.
up_speed = speedtest.Speedtest()
print(f' {up_speed.uploadO/8000000: .2f}mb')
Output:
85.31mb
16 | Python Reserved keywords
If you want to know the reserved keywords in Python, you can
use the help() function. Remember, you cannot use any
of these words as variable names. Your code will
generate an error.
pri nt(help('keywords'))
Output:
Here is a list of the Python keywords, Enter any
keyword to get more help.
None
17 । Properties and Methods
If you want to know the properties and methods of an object or
module, use the dir() function. Below, we are checking for the
properties and methods of a string object. You can also use dir()
to check the properties and methods of modules. For instance,
if you wanted to know the properties and methods of the
collections module, you could import it and pass it as an
argument to the function print(dir(collections)).
a = 'I love Python'
pri nt(di r(a))
Output:
['__ add__ '______ class__ '______ contains__ '______ delattr__
'__ dir__ ', '__ doc__ ’, '__ eq__ ’, '__ format__ '______ ge__
'__ getattribute__ ', '__ getitem__ ', '__ getnewargs__
'_ gt__ '_____ hash___ '______ init_ ’ , '___ init_subclass__
'_ iter___' , '__ le__ ' , '__ Ten___' , '__ It__ ' , '__ mod__
'__ mul__ ' , '__ ne__ ' , '__ new__ ' , '__ reduce__
'__ reduce_ex__ ' , '__ repr__ ' , '__ rmod__ ' , '__ rmul__
'__ setattr__ '_______________ sizeof__ '_______________ str__
'__ subclasshook__ 'capitalize', 'casefold', 'center
'count', 'encode', 'endswith', 'expandtabs', 'find
'format', 'format_map', 'index', 'isal num', 'isalpha
'isascii', 'isdecimal', 'isdigit', ' isidentifier
'islower', 'isnumeric', 'isprintable' , 'isspace
'istitle', 'isupper', 'join', 'ljust', 'lower
'Istrip', 'maketrans', 'partition', 'removeprefix
'removesuffix', 'replace', 'rfind', 'rindex', 'rjust
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines
'startswith', 'strip', 'swapcase', 'title', 'translate
'upper', 'zfil 1 ' ]
18 | Open a Website Using Python
Did you know that you can open a website using a Python
script?
You can also specify if you want to open a new tab in a browser
or a new browser window. See the code below:
import webbrowser
url = "https://www.google.com/ "
Now, if there is more than one most frequent item in the string,
the max() function will return the element that comes first
alphabetically. For example, if the string above had 4 Fs and 4 Ss,
the max function would return "f" instead of "s" as the most
frequent element because "f" comes first alphabetically.
We can also use the Counter class from the collections module.
The most_commonO method of this class will count how many
times each element appears in the list, and it will return all the
elements and their counts, as a list of tuples. Below, we pass the
parameter (1) because we want it to return the number one most
common element of the list. If we pass (2), it will return the two
most common elements.
import collections
a = 'fecklessness'
printfcollections.Counter(a).most_common(l))
Output:
('s', 4)
20 I Memory Size Check
Do you want to know how much memory an object is consuming
in Python?
The sys module has a method that you can use for such a task.
Here is a code to demonstrate this. Given the same items, which
one is more memory efficient among a set, a tuple, and a list?
Let's use the sys module to find out.
import sys
As you can see, lists and tuples are more space efficient than
sets.
■
try:
iter_check = iter(arr)
except TypeError:
print('object a not iterable')
else:
print('object a is iterable')
try:
iter_check = iter(b)
except TypeError:
print('object b is not iterable')
else:
print('object b is iterable')
Output:
Object a is iterable
Object b is not iterable
23 I Sorting a List of Tuples
You can sort a list of tuples using the itemgetterQ class of the
operator module. The itemgetterQ function is passed as a key
to the sortedQ function. If you want to sort by the first name,
you pass the index (o) to the itemgetterQ function. Below are
different ways you can use itemgetterQ to sort the list of tuples.
names = [('Ben','Jones'),('Peter','Parker'),
('Kelly','Isa')j
We can also access the article text, using the text method.
news = Article("https://indianexpress.com/article/"
"technology/gadgets/"
"apple-di sconti nues-i ts-1ast-i pod-model-7910720/")
news.downloadO
news.parsed
print(news.text)
Output:
Apple Inc.’s iPod, a groundbreaking device that upended the
music and electronics industries more than two decades ago...
Below, we have set the start parameter to one (1). You can start
with any number you want.
days = ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"]
days_tuples = 1ist(enumerate(days, start=l))
pri nt(days_tuples)
Output:
[(1, 'Sunday'), (2, 'Monday'), (3, 'Tuesday'), (4,
'Wednesday'), (5, 'Thursday'), (6, 'Friday'), (7, 'Saturday')]
It is also possible to create the same output with a for loop. Let’s
create a function to demonstrate this.
def enumerate(days, start= 1):
n = start
for day in days:
yield n, day
n += 1
lower_names = []
for item in name:
assert type(item) == str, 'non-string items in the list'
if item.islowerO :
lower_names.append(item)
Let’s say we want to find the index of the letter "n" in stn below.
Here is how we can use the enumerate function to achieve that:
strl = 'string'
If you don’t want to use a for loop, you can use enumerate with
the list function, and it will return a list of tuples. Each tuple will
have a value and its index.
strl = 'string'
str_counta = 1ist(enumerate(strl))
pri nt(str_counta)
Output:
[(0, 's'), (1, 't'), (2, 'r'), (3, '1'), (4, 'n'), (5, 'g')]
30 | Create Class Using Type Function
The type() function is usually used to check the type of an object.
However, it can also be used to create classes dynamically in
Python.
Below I have created two classes, the first one using the class
keyword and the second one using the type() function. You can
see that both methods achieve the same results.
# Creating dynamic class using the class keyword
class Car:
def __init__ (self, name, color):
self.name = name
self.color = color
def print_car(self):
return f'The car is {self.name} ' \
f'and its {self.color} in color'
carl = Car('BMW', 'Green')
print(carl.print_car())
Cars = type("Car" , () ,
{'__ init__ ': cars_init,
'print_car':lambda self:
f'The car is {self.name} '
f'and its {self.color} in color'})
carl = Cars("BMW", "Green")
print(carl.print_car())
Output:
The car is BMW and its Green in color
The car is BMW and its Green in color
31 Checking if a String is Empty
The simple way to check if a given string is empty is to use the
if statement and the not operator, which will return a Boolean
value. Empty strings in Python evaluate to False, and strings
that are not empty evaluate to True. The not operator returns
True if something is False and False if something is True. Since
an empty string evaluates to False, the not operator will return
True. Below, if a string is empty, the if statement will evaluate
to True, so that part of the code will run. If a string is not empty,
the else statement will run.
# Empty string
strl = ' '
if not strl:
printf'This string is empty')
else:
printf'This string is NOT empty')
Output:
This string is empty
Example 2
if not strl:
printf'This string is empty')
else:
print('This string is NOT empty')
Output:
This string is NOT empty
32 | Flatten Nested List
What is a nested list? A nested list is a list that has another list as
an element (a list inside a list). You can flatten a nested list using
the sum() function. Note that this will work on a two-dimensional
nested list.
new_list = sum(nested_list,[])
pri nt(new_li st)
Output:
[2, 4, 6, 8, 10, 12]
Please note that this is not the most efficient way to flatten a list.
It is not easy to read. But it's still pretty cool to know, right? @
if file:
os. removeC'thisfile.txt")
else:
print('This file does Not exist')
Output:
This file does Not exist
34 I Set Comprehension
Set comprehension is similar to list comprehension; the only
difference is that it returns a set and not a list. Instead of square
brackets, set comprehension uses curly brackets. This is because
sets are enclosed in curly brackets. You can use set comprehension
on an iterable (list, tuple, set, etc.).
Let’s say you want to update the values of the dictionary from
integers to floats; you can use dictionary comprehension. Below,
k accesses the dictionary keys, and v accesses the dictionary
values.
dictl = {'Grade': 70, 'Weight': 45, 'Width': 89}
# Converting diet values into floats
dict2 = {k: float(v) for (k, v) in dictl.itemsQ}
print(dict2)
Output:
{'Grade': 70.0, 'Weight': 45.0, 'Width': 89.0}
df = pd.DataFrame(list(zip(listl, models)),
index =[1, 2, 3] ,
columns=['Brands','Models'])
pri nt(df)
Output:
Brands Models
1 Tesla X
2 Ford Focus
3 Fiat Doblo
39 I Adding a Column to a DataFrame
Let’s continue with the tip from the previous tip (38). One of the
most important aspects of pandas DataFrame is that it is very
flexible. We can add and remove columns. Let’s add a column
called Age to the DataFrame. The column will have the ages of
the cars.
import pandas as pd
listl = ['Tesla', 'Ford', 'Fiat']
models = ['X', 'Focus', 'Doblo']
df = pd.DataFrame(list(zip(listl,models)),
index =[1, 2, 3] ,
columns=['Brands','Models'])
# Adding a column to data Frame
df['Age'] = [2, 4, 3]
pri nt(df)
Output:
Brands Models Age
1 Tesla X 2
2 Ford Focus 4
3 Fiat Doblo 3
def timer(func) :
def innerO :
start = time.perf_counterO
funcO
end = time.perf_counterO
printff'Run time is {end-start:.2f} secs')
return inner
©timer
def range_tracker():
1st = []
for i in range(lOOOOOOO):
1st.append(i**2)
range_trackerO
Output:
Run time is 10.25 secs
41 List Comprehension vs Generators
A generator is similar to a list comprehension, but instead of
square brackets, you use parenthesis. Generators yield one item
at a time, while list comprehension releases everything at once.
Below, I compare list comprehension to a generator in two
categories:
1. Speed of execution.
2. Memory allocation.
Conclusion
import timeit
import sys
# function to check time execution
def timer(_, code):
exc_time = timeit.timeit(code, number=1000)
return f'{„}: execution time is {exc_time:.2f}'
# function to check memory allocation
def memory_size(_, code):
size = sys.getsizeof(code)
return f'{_}: allocated memory is {size}'
one = 'Generator'
two = 'list comprehension'
print(timer(one, 'sumC(num**2 for num in range(10000)))'))
print(timer(two, 'sum([num**2 for num in range(lOOOO)])'))
print(memory_size(one,(num**2 for num in range(lOOOO))))
print(memory_size(two,[num**2 for num in range(lOOOO)]))
Output:
Generator: execution time is 5.06
list comprehension: execution time is 4.60
Generator: allocated memory is 112
list comprehension: allocated memory is 85176
42 Writing to File
Let’s say you have a list of names and you want to write them
in a file, and you want all the names to be written vertically.
Here is a sample code that demonstrates how you can do it.
The code below creates a CSV file. We tell the code to write
each name on a new line by using the escape character C\n').
Another way you can create a CSV file is by using the CSV
module.
names = ['John Kelly', 'Moses Nkosi', 'Joseph Marley']
with open('names.csv', 'w') as file:
for name in names:
file.write(name)
file.write('\n')
import PyPDF2
from PyPDF2 import PdfFileMerger, PdfFileReader,
merge = PyPDF2.PdfFileMerger(strict=True)
for file in listl:
merge.append(PdfFileReader(file,'rb+'))
For this code to run successfully, make sure that the files
you are wanting to merge are saved in the same location as
your Python file. Create a list of all the files that you are
trying to merge. The output simply confirms that the
merged file has been created. The name of the file is
mergedfile.pdf.
1
44 Return vs Yield
Do you understand the distinction between a return statement
and a yield statement in a function? The return statement returns
one element and ends the function. The yield statement returns
a "package" of elements called a generator. You have to "unpack"
the package to get the elements. You can use a for loop or the
next() function to unpack the generator.
pri nt(num(5))
Output:
0 ’
You can see from the output that once the function returns o, it
stops. It does not return all the numbers in the range.
# creating a generator
gen = num(5)
#unpacking generator
for i in gen:
pri nt(i, end = '')
Output:
01234
Did you know that you can correct grammar errors in text using
Python? You can use an open-source framework called Gramformer.
Gramformer (created by Prithviraj Damodaran) is a framework for
highlighting and correcting grammar errors in natural-language text.
Here is a simple code that demonstrates how you can use
gramformer, to correct errors in a text.
sentences = [
'I hates walking night',
'The city is were I work',
'I has two children'
]
pri nt(thi s)
Output:
The Zen of Python, by Tim Peters
pp = pprint.PrettyPrinter(sort_dicts=True)
pp.ppri nt(a)
Output:
{'b': 3, 'c': 2, 'x': 10, 'y': 5}
Please note that pprint does not change the order of the actual
dictionary; it just changes the printout order.
Insert underscore
pp = pprint.PrettyPrinter(underscore_numbers=True)
pp.ppri nt(arr)
Output:
[l_034_567, 1_234_567, 1_246_789, 12_345_679, 987_654_367]
49 Convert Picture to Grey Scale
Do you want to convert a color image into grayscale? Use
Python’s cv2 module.
#Save image
cv.imwriteCgrayed.jpg' , grayed_img)
50 Time it with timeit
If you want to know the execution time of a given code, you can
use the timeitQ module. Below, we create a function called timer
that uses timeitQ from the timeit module. We're basically using
timeit to determine how long it takes to run sum(num**2 for
num in range(ioooo)).The first parameter of the timeit
function in the code below is stmt. This is where we pass the
Python code that we want to measure. This parameter only takes
a string as an argument, so we have to ensure that we convert our
code to a string format. The number parameter is basically the
number of executions we want to run on this code.
import timeit
def timer(code):
tm = timeit.timeit(code,number=1000)
return f'Execution time is {tm:.2f} secs.'
It’s not necessary to create a function like we did above. You can
also use timeit without creating a function. Let’s simplify the
above code by writing it without a function. Remember that the
stmt parameter only takes a string as an argument; that is why
the test variable below, which is the code that we pass to the
timeitQ function, is a string.
import timeit
Once you install it, you can import it into your script. The
function below demonstrates how we can use pyshorteners.
We pass a very long URL to the function, and it returns a short
URL.
import pyshorteners
pri nt(shorter_url(
"https://www.google.com/search?q=python+documentati on&newwind
ow=l&sxsrf=ALiCzsYze-"
"G2AArMZtCrJfyfVcqq6z8Rwg%3A1662044120968&ei=2McQY4PaOp68xc8P
yp-qIA&oq=python+do&gs_lcp="
"Cgdnd3Mtd216EAEYATIFCAAQgAQyBQgAEIAEMgUIABCABDIFCAAQgAQyBQgA
EIAEMgUIABCABDIFCAAQg"
"AQyBQgAEIAEMgUIABCABDIFCAAQgAQ6BwgAEEcQsAM6DQguEMcBENEDELADE
EM6BwgAELADEEM6BAgj"
"ECc6BAgAEEM6BAg U ECdKBAh BGAB KBAhGGABQlxBY70JgxlVoAXAB eACAAYg B
i AGWCJIBAzAuOZg BA"
"KABAcgBCsABAQ&scli ent=gws-wi z"))
Output
('Short url is', 'https://tinyurl.com/2n2zpl8d')
52 The Round Function
How do you easily round off a number in Python? Python has a
built-in round function that handles such tasks. The syntax is:
You can see that we have two digits after the decimal point. If
we didn’t pass the second parameter (2), the number would be
rounded to 23.
To round up or down a number, use the ceil and. floor methods
from the math module. The ceil rounds up a number to the
nearest integer greater than the given number. The floor
method rounds down a number to the nearest integer that is less
than the given number.
import math
a = 23.4567
# rounding up
print(math.ceil (a))
# rounding down
pri nt(math.floor(a))
Output:
24
23
53 I Convert PDF Files to Doc
Did you know that you can convert a PDF file to a Word
document using Python?
Python has a library called pdf2docs. With this library, you can
convert a pdf file to a word document with just a few lines of
code. Using pip, install the library;
instantiate converter
cv = Converter(pdf)
cv.convert(word_file)
#close file
cv.closeO
54 I Text from PDF File
pri nt(pandas)
Output:
<module 'pandas' from
'C:\\Users\\Benjamin\\AppData\\Local\\Programs\\Pytho
n\\Python3io\\lib\\site-packages\\pandas\\__ init__ .py'>
num = '979117528719'
# saving image as png
bar_code = ISBN13(num, writer=ImageWriter())
# save image
bar_code.save('bar_code')
# read the image using pillow
img = Image.open("bar_code.png")
i mg.show()
Output
57 I Indices Using Len & Range
Functions
If you want to get the indices of items in a sequence, such as a
list, we can use the len() and range() functions if you don’t want
to use the enumerateQ function. Let’s say we have a list of
names and we want to return the indices of all the names in the
list. Here is how we can use the len() and range() functions:
names = ['John', 'Art', 'Messi']
for i in range(len(names)):
print(i, names[i])
Output:
0 John
1 Art
2 Messi
for i in rangefien(names)):
if namesfi] == 'Messi':
printff'The index of the name {names[i]J is {i}')
break
Output:
The index of the name Messi is 2
58 | Convert Emoji to Text
Did you know that you can extract text from emojis? Let’s say
you have a text with emojis and you don’t know what the emojis
mean. You can use a Python library to convert the emojis to text.
import demoji
txt = "I spent the day at Today its very C® I cant wait for winter
demoji.findal1 'txt |
Output
’fire r,
'cold1 face",
' person lifting weights ' .
'het face }
59 Currency Converter
In Python, with just a few lines of code, you can write a program
that converts one currency into another using up-to-date
exchange rates. First, install the forex library using: pip install
forex-python
The code below will convert any currency. You just have to know
the currency codes of the currencies you are about to work with.
Try it out.
from forex_python.converter import CurrencyRates
# Instantiate the converter
converter = CurrencyRatesO
def currency_converter():
# Enter the amount to convert
amount = i nt(i nput("Please enter amount to convert: "))
# currency code of the amount to convert
from_currency = input("Enter the currency code of "
"amount you are converting : ").upper()
# currency code of the amount to convert to
to_currency = input("Enter the currency code you "
"are converting to: ").upper()
# convert the amount
converted_amount = converter.convert(from_currency,
to_currency, amount)
return f' The amount is {converted_amount:,2f} and ' \
f'the currency is {to_currency}'
pri nt(currency_converter())
6o Generate Custom Font
Python has a cool library that you can use to generate custom
fonts. This library is designed for the purpose of creating fancy
texts for our programs. For example, we can use a generated
font to create a cool article title. Below, we are going to
demonstrate how we can create a fancy title with the module.
Install with pip;
You can also generate a list of fonts that you can use for your text.
Run this code below and you will get a list of fonts that are
available.
import pyfiglet
# Language to detect
lang = detect("* • • • ")
pri nt(lang)
Output:
ja
6 2 I Refresh URL with Selenium
Did you know that you can refresh a URL using Python?
Usually, to refresh a page, we have to do it manually. However,
we can automate the process with just a few lines of code. We
will use the selenium module for this. Install the following:
Now, let’s write the code. I am using the Chrome web browser,
so I will need Chrome dependencies. If you are using another
browser, you will need to install a driver for that browser. So,
we need the URL link of the website that we want to open. The
time is the number of seconds we want to wait before refreshing
the page. The code will automatically refresh the page once the
waiting time is over.
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
# Url to open and refresh
url = "url to open and refresh"
driver.get(url)
# waiting time before refresh
time.sleep(lO)
driver, refreshO
63 | Substring of a String
if 'like' in s:
print('Like is a substring of s')
else:
print('Like is not a substring of s')
Output:
Like is a substring of s
We can also use the "not in" operator. The "not in" operator is
the opposite of the in operator.
s = 'Please find something you like'
if 'like' not in s:
print('Like is not a substring of s')
else:
print('Like is a substring of s')
Output:
Like is a substring of s
difference = set(a).difference(set(b))
pri nt(list(di fference))
Output:
[8, 4, 6]
difference = []
for number in a:
if number not in b:
di fference.append(number)
pri nt(di fference)
Output:
[6, 8, 4]
You can also convert the above code into a list comprehension.
a = [9, 3, 6, 7, 8, 4]
b = [9, 3, 7, 5, 2, 1]
strl = s.decodeQ
pri nt(type(strl))
pri nt(strl)
Output:
cclass 'str'>
Love for life
67 | Multiple Input from User
What if you want to get multiple inputs from a user? How do you
do it in Python? Python uses the input() function to get input
from the user. The input() function takes one input at a time;
that’s the default setting. How can we modify the input function
so it can accept multiple inputs at a time? We can use the input()
function together with the string method, split(). Here is the
syntax below:
input().split()
With the help of the split() function, the input() function can
take multiple inputs at the same time. The split() method
separates the inputs. By default, the split method separates
inputs right at the whitespace. However, you can also specify a
separator. Below, we ask a user to input three (3) numbers. We
use the split() method to specify the separator. In this case, we
separate the inputs with a comma (,). Then we calculate the
average of the three numbers. If the inputs are 12, 13, and 14,
we get the output below:
a, b, c = input("Please input 3 numbers: ").split(sep=',')
pri nt(n)
Output:
['Kelly', ' John', ' Trey', 'Steven']
68 The _iter_() Function
If you want to create an iterator for an object, use the iterQ
function. Once the iterator object is created, the elements can
be accessed one at a time. To access the elements in the iterator,
you will have to use the next() function. Here is an example to
demonstrate this:
names = ['jake', "Mpho", 'Peter']
# Creating an iterator
iter_object = iter(names)
# Accessing items using next function
namel = next(iter_object)
print('First name is', namel)
name2 = next(iter_object)
print('Second name is', name2)
name3 = next(iter_object)
print('Third name is', name3)
Output:
First name is jake
Second name is Mpho
Third name is Peter
Because the list only has three elements, attempting to print the
fourth element in the iterable will result in a Stopiteration
error.
dictl = dict(zip(listl,list2))
pri nt(di ctl)
Output:
{'name': 'Yoko', 'age': 60, 'country': 'Angola'}
dictl = dict(zip(listl,list2))
pri nt(di ctl)
Output:
{'name': 'Yoko', 'age': 60, 'country': 'Angola'}
70 Finding Permutations of a string
Permutations of a string are different orders in which we can
arrange the elements of the string. For example, given an "ABC"
string, we can rearrange it into ["ABC," "ACB," "BAC," "BCA,"
"CAB," "CBA."]. In Python, the easiest way to find permutations
of a string is to use itertools. Itertools has a permutation class.
Here is how we can do it, using itertools.
for i in range(len(string)):
char = string[i]
s = string[O:i] + string[i + 1:]
find_permute(s, j + char)
return j
print(find_permute('ABC', ''))
Output:
ABC ACB BAC BCA CAB CBA
71 Unpacking a List
Sometimes you want to unpack a list and assign the elements to
different variables. Python has a method that you can use to
make your life easier. We can use the Python unpacking
operator, asterisk (*). Below is a list of names. We want to get
the boy’s name and assign it to the variable "boy_name." The
rest of the names will be assigned to the variable "girls_name."
So, we assign (unpack from the list) the first item on the list to
the boy variable. We then add to the girls_name variable.
By adding * to the girl’s name, we are basically telling Python
that once it unpacks the male name, all the other remaining
names must be assigned to the girls_name variable. See the
output below:
names = [ 'John', 'Mary', 'Lisa’, ‘Rose’]
If the name "John" was at the end of the list, we would put the
name with the asterisk at the beginning. See below:
names = [ 'Rose', 'Mary', ’Lisa’, ‘John']
Why type hints? Type hints simply help to make the code more
readable and more descriptive. By just looking at the hint
annotations, a developer will know what is expected of the
function.
73 I File Location
import os
You can see from the output that we have popped elements from
both ends of the list.
75 I Python ChainMap
What if you have a number of dictionaries and you want to
wrap them into one unit? What do you use? Python has a class
called chainMap that wraps different dictionaries into a single
unit. It groups multiple dictionaries together to create one
unit. ChainMap is from the collections module. Here is how it
works:
from collections import ChainMap
dictl = ChainMap(x, y)
dictl = ChainMap(x, y)
Let’s say you have a range of 100000 that you want your loop to
run through, and after every loop, you want your code to sleep
for 0.001 sec. Here's how to do it with tqdm so you can monitor
the loop's progress. When you run this code, you will get the
progress meter below as the output.
for i in tqdm(range(100000)):
pass
time.sleep(0.001)
Output:
9%|| | 85Q3/1000GO [02:12<27:29, 55.48it/s]|
You can now see the word "progress" in the progress meter. You
can put in whatever description you want. Explore the module
some more.
I
import pywhatkit
import cv2 as cv
Python is
78 | Taking a Screenshot
You can take a screenshot with Python. Python has a library
called pyautogui, which is an automation tool. Install the
library using pip:
import pyautogui
import numpy as np
import cv2 as cv
# Taking screenshot
image = pyautogui.screenshot()
image.save('my_screenshot.png')
# convert RGB 2 BGR
image = cv.cvtColor(np.array(image),
CV.C0L0R_RGB2BGR)
cv.imshow("image", image)
cv.waitKey(O)
cv.destroyAllWindows()
79 Return Multiple Function Values
By default, a function returns one value, and it stops. Below, we
have 3 values in the return statement. When we call the
function, it returns a tuple of all three items.
def values():
return 1, 2, 3
pri nt(values())
Output:
(1, 2, 3)
x, y, z = valuesQ
pri nt(x)
print(y)
pri nt(z)
Output:
1
2
3
8o Download YouTube Videos
Python makes it super easy to download YouTube videos. With
just a few lines of code, you will have your favorite videos saved
on your computer. The Python library that you need to
download videos is pytube. Install it with:
First, we import the module into our script. We then get the link
to the video we are trying to download.
from pytube import YouTube
yt_video = YouTube ("<video link> )
We then download the file. You can also input the path where
you want the file to be saved.
V_file.download("path to save file.")
81 Convert a String to a List
In Python, we can easily convert a string to a list of strings. We
can combine the list() function with the map() function. The
map function returns a map object, which is an iterator. The
mapO function takes two arguments: a function and an iterable.
Below, the list is an iterable, and str() is the function. We then
use the list() function to return a list. The split() method divides
or splits a string at whitespaces.
strl = 1ist(map(str,s.split()))
pri nt(strl)
Output:
['I', 'love', 'Python']
You can convert a list of strings back to a string using the map()
function in conjunction with the join() method. Let’s convert
the output of the above code back to a string using the map()
and JoinO methods.
listl = ['Ilove'Python']
You can see from the output that we have combined the two lists
using the zip() function. We have paired the first names with
the last names.
83 I Extend vs. Append
Extend and append are both list methods. They both add
elements to an existing list. The appendQ method adds one (1)
item to the end of the list, whereas the appendQ method does
not. The extendQ method adds multiple items to the end of the
list. Below, we use the appendQ method to append numbers2
to numbersi. You can see that the whole list of numbers2 has
been appended to numbersi as one (1) item.
numbersi = [1, 2, 3]
numbers2 = [4, 5, 6]
class Cars:
__ slots__ = ["make", 'brand']
So why use slots? We use slots because they help save memory
space. Class objects take up less space when we use slots. See
the difference in object size in the following examples:
import sys
class Cars:
def __ init__ (self, make, brand):
self.make = make
self.brand = brand
Example 2
class Cars:
__ slots__ = ["make", 'brand']
You can see from the outputs above that using slots saves
memory space.
8 5 ! Watermark Image with Python
With just a few lines of code, we can watermark our images
using Python. We are going to use the pillow library for this
task. Install the pillow module using:
Let’s now import the classes from the pillow module and write
the code that we need to watermark this image.
from PIL import ImageDraw
from PIL import image
from PIL import imageFont
fake = Faker()
for i in range(20):
pri nt (fake. countryO)
Output:
Cameroon
Tajikistan
Ethiopia
Li echtenstei n
Netherlands
Grenada
Switzerland
Si ngapore
Estoni a
San Marino
Maiaysi a
New Zealand
Azerbai jan
Monaco
British Indian Ocean Territory (Chagos Archipelago)
Brazil
Austri a
Saint Barthelemy
Zimbabwe
Korea
Since this is random, every time you run it, it will generate a
different list of countries.
You can also generate profile data using this model. Below,
we generate profile data and pass it to pandas to generate a
Pandas DataFrame.
rom faker import Faker
import pandas as pd
fake = FakerO
0 jhanson Steven Kennedy M 8563 Jackson Crest Suite 324'nLawnenceland, GA. ctumer@h otm ail .com 1964-08-17
1 akane Dana Marlin F 025 Love ManorinMeganstad. CA 83700 longbianca@gmail com 1961-11-07
2 vmcbride Ariel Greene F 3939 Cynthia Rapids Suite 794\nWesl Devin berg youngjoel (ghctma il .com 1912-03-2S
3 stephanienguyen Rebecca Young F 71951 Zimmerman OverpassinWest Sonya. FL 82366 benja m inwil I is ©g m a il .com 1945-11-09
4 frosirichard Suzanne Walker F 073 Lopez Neck Suite 940inPor1 Sarahshire NY joseboyer@h otm a il .com 1975-07-14
6 raber125 Anthony James U 2801 Roth MotorwaytfiKew Debra. OH 05797 gbell@yahoo.com 1507-09-04
6 dennis64 Crystal Stevenson F 344 Gray Loop Apt. 303\nLake Lindsay IN 22871 rinriglasl3aFbara@yahoo.com 1959-11-29
7 chentimolhy Vicki Hanson F 6751 Rios Ways Apt D16\nBrownvillc. NH 66161 hendersonjames@g ma il .com 1932-03-1S
1! Irodriguez Eric Rodrigue? M 3267 John Loop Suite 346inLake Sandraporl AL jacob48@y a h oo.com 1964-06-11
9 a ma nd a kirn Paul Tanner M 337 Le Ferry Suite 142lnLake Carla haven. MT 46444 frenchmanuel@yahoo.com 1996-08-28
There are many other types of data that you can generate with
this module. Explore the module further.
88 Flatten a list with more_itertools
There are many ways to flatten a list. We have covered other
methods already. There is another way we can flatten a nested
list. We can use a module called more_itertools. We will use
the collapseQ class from this module. This is a one-line
solution. First, install the module using:
return prime_num
pri nt(prime_numbers())
91 | RAM & CPU Usage
Do you want to know the resources your machine is using?
Python has a library called psutil that calculates the resource
usage of a computer. You can find out how much RAM and
CPU your computer is using with just a few lines of code.
Install the library using pip:
memory = psutil.virtual_memory()
def ram_usage():
print(f'Total available memory in gigabytes '
f'{memory.total/(1024**3):.3f}')
print(f1Total used memory in gigabytes '
f'{memory.used/(1024**3):.3f}')
print(f'Percentage of memory under use:'
f' {memory.percent}%')
ram_usage()
Output:
Total available memory in gigabytes 7.889
Total used memory in gigabytes 6.960
Percentage of memory under use: 88.2%
cpu_core = psutil.cpu_percent(percpu=True)
You can see from the outputs that the joinQ method is faster
than concatenation. If you want faster code, use the joinQ
method. However, you should note that the joinQ method
executes faster when you have more strings to join (more than
3 strings, at least). The concatenation method executes slower
because for every concatenation, Python has to create a string
and allocate memory. This slows down the process. But by
using thejoinQ method, Python only creates one string. This
makes the process much faster. Try running the code and
documenting your findings. Note that your execution times
will be different from my output.
93 I Recursion Limit
Do you want to know the recursion limit in Python? You can use
the sys module. Here is the code below:
import sys
pri nt(sys.getrecursionlimit())
Output:
1000
import sys
sys.setrecursionlimit(1200)
pri nt(sys.getrecursionlimit())
Output:
1200
You can see that the limit has changed from 1000 to 1200. So,
if you ever get a maximum recursion depth error, just make the
adjustment.
94 Country Info Using Python
country = Countrylnfo("Zambia")
pri nt(country.provi ncesQ)
Output:
['Central', 'Copperbelt' , 'Eastern', 'Luapula',
'Lusaka', 'North-Western', 'Northern', 'Southern',
'Western']
country = Countrylnfo("China")
pri nt (country .currenciesO)
Output:
['CNY']
95 Factorial Using One Line
We saw earlier how we can calculate the factorial of a number
using a function. Do you know that you can write a one-line
function that calculates the factorial of a number? To make this
work, we are going to need the reduce function from itertools and
the lambda function.
from functools import reduce
num = 7
You can change the num variable to any integer number and it
will still spit out a factorial of that number. Only one line of
code—how cool is that? Let’s try io.
from functools import reduce
num = 10
Below, we pass a string to textblob that has spelling errors. You can
see that the errors have been replaced with the correct spelling.
Textblob will pick the most likely correct word for the misspelled
word.
from textblob import TextBlob
Another interesting thing about this library is that you can use
it to pluralize words. See below:
from textblob import word
pri nt(check_list([1,1,1]))
Output:
True
So, the code above returns True because all the elements in the
list [1, 1, 1] are identical. What if the elements are not identical?
Let’s see what happens.
def check_list(arr : list):
return all(arr[0] == arr[i] for i in arr)
pri nt(check_list([1,1,2,3]))
Output:
False
If you just want to check if a string contains a bad word, you can
use the contains_profanity() method, which will return a Boolean
value of True if it contains profanity and False if it has no profanity.
text = 'I hate this shit so much'
censored_text = profanity.censor(text)
pri nt(censored_text)
Output:
People that love **** are ****
99 Monotonic or Not?
How do you check if an array is monotonic? An array is
monotonic if the elements are sorted either in descending order
or ascending order. For example, [4, 5, 5, 7] is monotonic. [4,
10, 2, 5] is not monotonic. We use the all() function to check if
the numbers in the array are ascending or descending. If they
are ascending or descending, it will return True. If they are not,
it will return False.
def check_monotonic(arr: list):
if all(arr[i] >= arr[i + 1] for i in rangeflen(arr)-1)):
return True
elif all(arr[i] <= arr[i + 1] for i in rangeflen(arr)-1)):
return True
else:
return False
listl = [4, 5, 5, 7]
pri nt(check_monotonic(listl))
Output:
True
The code returns True because [4, 5,5, 7] is monotonic. If we try [4,10,
2, 5], here is what we get:
def check_monotonic(arr: list):
if all(arr[i] >= arr[i + 1] for i in rangeflen(arr)-1)):
return True
elif all(arr[i] <= arr[i + 1] for i in rangeflen(arr)-1)):
return True
else:
return False
pri nt(number_factors(8))
Output:
1 '
2
4
8