100 Python Tips Tricks 1704521617
100 Python Tips Tricks 1704521617
Output:
1 3 6 7
Method 1
Using the merge ( | ) operator.
name1 = {"kelly": 23,
"Derick": 14, "John": 7}
name2 = {"Ravi": 45, "Mpho": 67}
Method 2
Using the merge ( ** ) operator. With this operator, you need to
put the dictionaries inside the curly brackets.
name1 = {"kelly": 23,
"Derick": 14, "John": 7}
name2 = {"Ravi": 45, "Mpho": 67}
month = calendar.month(2022, 4)
print(month)
Output:
April 2022
Mo Tu We Th Fr Sa Su
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
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.isleap(2022)
print(month)
Output:
False
4 | Get Current Time and Date
The below code demonstrates how you can get the current time
using the datetime() module. The strftime() method formats
time for the desired output. This code breaks down how you can
use the datetime module with the strftime() 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 today() method. See
below:
from datetime import date
today_date = date.today()
print(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.
list1 = [2, 5, 6, 8, 1, 8, 9, 11]
list1.sort(reverse=True)
print(list1)
Output:
[11, 9, 8, 8, 6, 5, 2, 1]
print('x is', x)
print('y is', y)
Output:
x is 30
y is 20
# step one
x ^= y
# step two
y ^= x
# step three
x ^= y
count_peter = Counter(list1).get("Peter")
print(f'The name Peter appears in the list '
f'{count_peter} times.')
Output:
The name Peter appears in the list 2 times.
newlist = []
for list2 in list1:
for j in list2:
newlist.append(j)
print(newlist)
Output:
[1, 2, 3, 4, 5, 6]
Using itertools
import itertools
flat_list = list(itertools.chain.from_iterable(list1)))
print(flat_list)
Output:
[1, 2, 3, 4, 5, 6]
You can also use the abs() function on a floating number, and
it will return the absolute value. See below:
a = -23.12
print(abs(a))
Output:
23.12
Using startswith()
list1 = ['lemon','Orange',
'apple', 'apricot']
Using endswith()
list1 = ['lemon','Orange',
'apple', 'apricot']
results = [12, 34, 67, 98, 90, 68, 55, 54, 64, 35]
print(sort_list(results))
Output:
[98, 90, 68, 67, 64]
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.nsmallest(5, results))
Output:
[12, 34, 35, 54, 55]
14 | 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
counter() from the collections module. The counter() 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'
print(Counter(a)==Counter(b))
Output:
True
if sorted(a)== sorted(b):
print('Anagrams')
else:
print("Not anagrams")
Output:
Anagrams
15 | 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.
d_speed = speedtest.Speedtest()
print(f'{d_speed.download()/8000000:.2f}mb')
Output:
213.78mb
up_speed = speedtest.Speedtest()
print(f'{up_speed.upload()/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.
print(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'
print(dir(a))
Output:
['__add__', '__class__', '__contains__', '__delattr__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getnewargs__',
'__gt__', '__hash__', '__init__', '__init_subclass__',
'__iter__', '__le__', '__len__', '__lt__', '__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', 'isalnum', 'isalpha',
'isascii', 'isdecimal', 'isdigit', 'isidentifier',
'islower', 'isnumeric', 'isprintable', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower',
'lstrip', 'maketrans', 'partition', 'removeprefix',
'removesuffix', 'replace', 'rfind', 'rindex', 'rjust',
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swapcase', 'title', 'translate',
'upper', 'zfill']
18 | Open a Website Using Python
Did you know that you can open a website using a Python
script?
To open a website using Python, import the webbrowser
module. This is a built-in module, so you don’t have to install
anything. Below, we are trying to open google.com using the
open() method of the module. You can do this with any website
if you know its URL.
import webbrowser
url = "https://www.google.com/"
open_web = webbrowser.open(url)
print(open_web)
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/"
# This opens a new tab in your browser
webbrowser.open_new_tab(url)
# This opens a new browser window
webbrowser.open_new(website)
19 | Most Frequent in a String
Let’s say you have a string and you want to find the most
frequent element in the string; you can use the max() function.
The max() function will count the items in the string and return
the item that appears the most. You just have to pass the string
count method to the key parameter. Let’s use the string below
to demonstrate this.
a = 'fecklessness'
most_frequent = max(a, key = a.count)
print(f'The most frequent letter is, '
f'{most_frequent}')
Output
The most frequent letter is, s
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_common() 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'
print(collections.Counter(a).most_common(1))
Output:
('s', 4)
20 | 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.
21 | Accessing Dictionary Keys
How do you access keys in a dictionary? Below are three
different ways you can access the keys of a dictionary.
print(set(dict1))
Output:
{'name', 'Country', 'student', 'age'}
print(sorted(dict1))
Output:
['Country', 'age', 'name', 'student']
22 | Iterable or Not
Question: How do you confirm if an object is iterable using
code?
This is how you can use code to check if an item is iterable or
not. We are using the iter() function. When you pass an item
that is not iterable as an argument to the iter() function, it
returns a TypeError. Below, we write a short script that checks
if a given object is an iterable.
arr = ['i', 'love', 'working', 'with', 'Python']
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 | Sorting a List of Tuples
You can sort a list of tuples using the itemgetter() class of the
operator module. The itemgetter() function is passed as a key
to the sorted() function. If you want to sort by the first name,
you pass the index (0) to the itemgetter() function. Below are
different ways you can use itemgetter() to sort the list of tuples.
names = [('Ben','Jones'),('Peter','Parker'),
('Kelly','Isa')]
a = lambda x: x[-1]
y = sorted(list1, key=a)
print(y)
Output:
['Peter', 'Mary', 'Kelly']
a = lambda x: x[:1]
y = sorted(list1, key=a)
print(y)
Output:
['Kelly', 'Mary', 'Peter']
list2 = sorted(list1)
print(list2)
Output
['Kelly', 'Mary', 'Peter']
25 | Access News Using Python
You can do a lot of things with Python, even read the news. You
can access the news using the Python newspapers module. You
can use this module to scrape newspaper articles. First, install the
module.
pip install newspaper3k
Below we access the title of the article. All we need is the article
URL.
from newspaper import Article
news = Article("https://indianexpress.com/article/"
"technology/gadgets/"
"apple-discontinues-its-last-ipod-model-7910720/")
news.download()
news.parse()
print(news.title)
Output
End of an Era: Apple discontinues its last iPod model
We can also access the article text, using the text method.
news = Article("https://indianexpress.com/article/"
"technology/gadgets/"
"apple-discontinues-its-last-ipod-model-7910720/")
news.download()
news.parse()
print(news.text)
Output:
Apple Inc.’s iPod, a groundbreaking device that upended the
music and electronics industries more than two decades ago...
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
print(list(enumerate(days)))
Output:
[(1, 'Sunday'), (2, 'Monday'), (3, 'Tuesday'), (4, 'Wednesday'), (5,
'Thursday'), (6, 'Friday'), (7, 'Saturday')]
27 | Assertion
We can use the assert statement to check or debug your code. The
assert statement will catch errors early on in the code. The assert
statement takes two arguments: a condition and an optional
error message. Here is the syntax below:
assert <condition>, [error message]
The condition returns a Boolean value of either True or False. The
error message is the message we want to be displayed if the
condition is False.
Below, we insert an assert statement in the code. This code takes
a list of names and returns all the names in lowercase letters. We
expect all the items in the list to be strings, so we use the insert
statement to debug for non-string entries. The insert statement
will check if all the items in the list are of type str. If one of the
items is not a string, it will evaluate to False. It will halt the
program and throw an AssertionError. It will display the error
message that "non-string items are in the list." If all the
items are strings, it will evaluate to True and run the rest of the
code. The code returns an error because the fourth name in the
list of names is not a string.
name = ["Jon","kelly", "kess", "PETR", 4]
lower_names = []
for item in name:
assert type(item) == str, 'non-string items in the list'
if item.islower():
lower_names.append(item)
print(lower_names)
Output:
AssertionError: non-string items in the list
If we remove the non-string item from the list, the rest of the
code runs.
name = ["Jon","kelly", "kess", "PETR"]
lower_names = []
for item in name:
assert type(item) == str, 'non-string items in the list'
if item.islower():
lower_names.append(item)
print(lower_names)
Output:
['kelly', 'kess']
28 | Print Colored Texts
Did you know that you can add color to your code using Python
and ANSI escape codes? Below, I created a class of codes and
applied it to the code that I printed out.
class Colors():
Black = '\033[30m'
Green = '\033[32m'
Blue = '\033[34m'
Magenta = '\033[35m'
Red = '\033[31m'
Cyan = '\033[36m'
White = '\033[37m'
Yellow = '\033[33m'
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.
str1 = 'string'
str_counta = list(enumerate(str1))
print(str_counta)
Output:
[(0, 's'), (1, 't'), (2, 'r'), (3, 'i'), (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'
Cars = type("Car",(),
{'__init__': cars_init,
'print_car':lambda self:
f'The car is {self.name} '
f'and its {self.color} in color'})
if not str1:
print('This string is empty')
else:
print('This string is NOT empty')
Output:
This string is empty
Example 2
Let's try to insert something into the string now.
# Not empty string
str2 = 'string'
if not str1:
print('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,[])
print(new_list)
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? 😊
os.remove("thisfile.txt")
Output:
FileNotFoundError: [WinError 2] The system cannot find the file
specified: 'thisfile.txt'
file = os.path.exists('thisfile.txt')
if file:
os.remove("thisfile.txt")
else:
print('This file does Not exist')
Output:
This file does Not exist
34 | 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.).
# Creating a function
def lower_names(n:str):
return n.islower()
df = pd.DataFrame(list(zip(list1,models)),
index =[1, 2, 3],
columns=['Brands','Models'])
print(df)
Output:
Brands Models
1 Tesla X
2 Ford Focus
3 Fiat Doblo
39 | 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
df = pd.DataFrame(list(zip(list1,models)),
index =[1, 2, 3],
columns=['Brands','Models'])
# Adding a column to dataFrame
df['Age'] = [2, 4, 3]
print(df)
Output:
Brands Models Age
1 Tesla X 2
2 Ford Focus 4
3 Fiat Doblo 3
def timer(func):
def inner():
start = time.perf_counter()
func()
end = time.perf_counter()
print(f'Run time is {end-start:.2f} secs')
return inner
@timer
def range_tracker():
lst = []
for i in range(10000000):
lst.append(i**2)
range_tracker()
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
List comprehension executes much faster but takes up more
memory. Generators execute a bit slower, but they take up less
memory since they only yield one item at a time.
import timeit
import sys
one = 'Generator'
two = 'list comprehension'
import PyPDF2
from PyPDF2 import PdfFileMerger, PdfFileReader,
merge = PyPDF2.PdfFileMerger(strict=True)
for file in list1:
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.
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.
Example 1: Using return statement
def num (n: int) -> int:
for i in range(n):
return i
print(num(5))
Output:
0
You can see from the output that once the function returns 0, it
stops. It does not return all the numbers in the range.
# creating a generator
gen = num(5)
#unpacking generator
for i in gen:
print(i, end = '')
Output:
01234
sentences = [
'I hates walking night',
'The city is were I work',
'I has two children'
]
print(this)
Output:
The Zen of Python, by Tim Peters
Please note that pprint does not change the order of the actual
dictionary; it just changes the printout order.
Insert underscore
Pprint can also be used to insert a thousand separator into
numbers. Pprint will insert an underscore as a thousand
separator. It has a parameter called underscore_numbers. All we
have to do is set it to True. See the code below:
import pprint
pp = pprint.PrettyPrinter(underscore_numbers=True)
pp.pprint(arr)
Output:
[1_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.
First install cv2 using > pip install opencv-python<
Below we are converting a color book image to grayscale. You
can replace that with your own image. You must know where
the image is stored.
When you want to view an image using CV2, a window will
open. The waitkey indicates how long we expect the display
window to be open. If a key is pressed before the display time is
over, the window will be destroyed or closed.
import cv2 as cv
img = cv.imread('book.jpg')
# show the original image
img1 = cv.imshow('Original', img)
cv.waitKey(5)
#Save image
cv.imwrite('grayed.jpg', grayed_img)
50 | Time it with timeit
If you want to know the execution time of a given code, you can
use the timeit() module. Below, we create a function called timer
that uses timeit() from the timeit module. We're basically using
timeit to determine how long it takes to run sum(num**2 for
num in range(10000)).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.'
if __name__ == "__main__":
print(timer('sum(num**2 for num in range(10000))'))
Output:
Execution time is 5.05 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
timeit() function, is a string.
import timeit
print(shorter_url(
"https://www.google.com/search?q=python+documentation&newwind
ow=1&sxsrf=ALiCzsYze-"
"G2AArMZtCrJfyfVcqq6z8Rwg%3A1662044120968&ei=2McQY4PaOp68xc8P
yp-qIA&oq=python+do&gs_lcp="
"Cgdnd3Mtd2l6EAEYATIFCAAQgAQyBQgAEIAEMgUIABCABDIFCAAQgAQyBQgA
EIAEMgUIABCABDIFCAAQg"
"AQyBQgAEIAEMgUIABCABDIFCAAQgAQ6BwgAEEcQsAM6DQguEMcBENEDELADE
EM6BwgAELADEEM6BAgj"
"ECc6BAgAEEM6BAguECdKBAhBGABKBAhGGABQ1xBY70JgxlVoAXABeACAAYgB
iAGWCJIBAzAuOZgBA"
"KABAcgBCsABAQ&sclient=gws-wiz"))
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:
round (number, number of digits)
The first parameter is the number to be rounded, and the
second parameter is the number of digits a given number will
be rounded to. That is the number of digits after the point. The
second parameter is optional. Here is an example:
num = 23.4567
print(round(num, 2))
Output:
23.46
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
print(math.floor(a))
Output:
24
23
53 | 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;
pip install pdf2docx
We are going to import the Converter class from this module.
If the file is in the same directory as your Python script, then
you can just provide the name of the file instead of a link. The
new doc file will be saved in the same directory.
#close file
cv.close()
54 | Text from PDF File
We can use the Python library PyPDF2 to extract text from
PDFs. First, install the library using pip;
pip install PyPDF2
We use the PdfFilereader class from the module. This class
will return the number of files in the pdf document, and it has
a get page method, which we can use to specify the page we
want to extract information from. Below, we extract text from
the book 50 Days of Python.
import PyPDF2
print(pandas)
Output:
<module 'pandas' from
'C:\\Users\\Benjamin\\AppData\\Local\\Programs\\Pytho
n\\Python310\\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")
img.show()
Output
57 | 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 enumerate() 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 range(len(names)):
if names[i] == 'Messi':
print(f'The index of the name {names[i]} 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.
First install the library.
Pip install demoji
The demoji library returns a dictionary of all the emojis in a text.
The emoji is the key, and the value is the emoji converted to text.
Output
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 = CurrencyRates()
def currency_converter():
# Enter the amount to convert
amount = int(input("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}'
print(currency_converter())
60 | 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;
pip install pyfiglet
The figlet_format() method takes two arguments: the text we
want to format and the font. The font parameter is optional. If
we do not pass an argument for the font, the default font will be
applied to our text.
import pyfiglet
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
print(pyfiglet.FigletFont.getFonts())
61 | Language Detector
You can detect language in a text using a Python library
called langdetect. At the moment, this detector supports
about 55 languages. Here are the supported languages
below:
af, ar, bg, bn, ca, cs, cy, da, de, el, en, es,
et, fa, fi, fr, gu, he,
hi, hr, hu, id, it, ja, kn, ko, lt, lv, mk, ml,
mr, ne, nl, no, pa, pl,
pt, ro, ru, sk, sl, so, sq, sv, sw, ta, te, th,
tl, tr, uk, ur, vi, zh - cn, zh - tw
print(lang)
Output:
ja
62 | 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:
pip install selenium
pip install webdriver-manager
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
driver.get(url)
# waiting time before refresh
time.sleep(10)
driver.refresh()
63 | Substring of a String
If you want to check if a string is a substring of another string,
you can use the in and not in operators. Let’s say we want to
test if "like" is a substring of string s. Here is how we do it using
the in operator: The in operator will evaluate to True if "like”
is a substring of s and False if it is not.
s = 'Please find something you like'
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
print(s.find('something'))
Output:
12
64 | Difference Between Two Lists
If you have two lists and you want to find the difference
between the lists, that is, elements that are in list a but not
in list b, use the set().difference(set()) method.
a = [9, 3, 6, 7, 8, 4]
b = [9, 3, 7, 5, 2, 1]
difference = set(a).difference(set(b))
print(list(difference))
Output:
[8, 4, 6]
difference = []
for number in a:
if number not in b:
difference.append(number)
print(difference)
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]
print(n)
Output:
['Kelly', ' John', ' Trey', 'Steven']
68 | The _iter_() Function
If you want to create an iterator for an object, use the iter()
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
name1 = next(iter_object)
print('First name is', name1)
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.
We can also elegantly put the next() function in a loop. See
below:
names = ['Jake', "Mpho", 'Peter']
iter_object = iter(names)
while True:
# accessing the items in object using next func
try:
print(next(iter_object))
except:
break
Output:
Jake
Mpho
Peter
dict1 = dict(zip(list1,list2))
print(dict1)
Output:
{'name': 'Yoko', 'age': 60, 'country': 'Angola'}
dict1 = dict(zip(list1,list2))
print(dict1)
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.
print(get_permutations('ABC'))
Output:
['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']
Another way to do it.
def find_permute(string, j ):
if len(string) == 0:
print(j, end=" ")
for i in range(len(string)):
char = string[i]
s = string[0: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']
import os
directory_path = os.getcwd()
print(directory_path)
You can see from the output that we have popped elements from
both ends of the list.
75 | 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
dict1 = ChainMap(x, y)
print(dict1)
Output:
ChainMap({'name': 'Jon', 'sex': 'male'}, {'name':
'sasha', 'sex': 'female'})
dict1 = ChainMap(x, y)
print(list(dict1.keys()))
print(list(dict1.values()))
Output:
['car', 'make', 'name', 'sex']
['bmw', 'x6', 'Jon', 'male']
76 | Progress Bar with Python
When you are executing loops (especially really large ones), you
can show a smart progress bar. A library called tqdm creates a
progress meter that keeps track of the progress of your loop. To
install the library, run:
Pip install tqdm
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:
You can now see the word "progress" in the progress meter. You
can put in whatever description you want. Explore the module
some more.
77 | Convert Text to Handwriting
You can convert text into handwriting with Python. Python has
a module called pywhatkit. Install pywhatkit using pip.
pip install pywhatkit
Below, we use pywhatkit to convert text to handwriting and
save it as an image. We then use the cv2 library to view the
image. Run this code below:
import pywhatkit
import cv2 as cv
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.COLOR_RGB2BGR)
cv.imshow("image", image)
cv.waitKey(0)
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
print(values())
Output:
(1, 2, 3)
x, y, z = values()
print(x)
print(y)
print(z)
Output:
1
2
3
80 | 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:
pip install pytube
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
map() 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.
str1 = list(map(str,s.split()))
print(str1)
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 join() methods.
list1 = ['I','love','Python']
str1 = ' '.join(map(str, list1))
print(str1)
Output:
I love Python
82 | Loop Over Multiple Sequences
What if you have two sequences and you want to loop over them
at the same time? How can you go about it in Python? This is
when the zip() function comes in handy. The zip() function
creates pairs of items in the sequences. The element at index
one in sequence one is paired with the element at index one in
sequence two. This process repeats for all the other indexes.
Let’s demonstrate how we can loop over two sequences at the
same time.
# list one
first_names = ['George','Keith', 'Art']
# list two
last_names = ['Luke', 'Sweat','Funnel']
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 | Extend vs. Append
Extend and append are both list methods. They both add
elements to an existing list. The append() method adds one (1)
item to the end of the list, whereas the append() method does
not. The extend() method adds multiple items to the end of the
list. Below, we use the append() method to append numbers2
to numbers1. You can see that the whole list of numbers2 has
been appended to numbers1 as one (1) item.
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
# using append method
numbers1.append(numbers2)
print(numbers1)
Output:
[1, 2, 3, [4, 5, 6]]
class Cars:
__slots__ = ["make", 'brand']
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.
85 | 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:
Pip install pillow
From this library, we are going to import ImageDraw,
ImageFont, and Image.
Below is the image we are going to use for demonstration from
https://www.worldwildlife.org/
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):
print(fake.country())
Output:
Cameroon
Tajikistan
Ethiopia
Liechtenstein
Netherlands
Grenada
Switzerland
Singapore
Estonia
San Marino
Malaysia
New Zealand
Azerbaijan
Monaco
British Indian Ocean Territory (Chagos Archipelago)
Brazil
Austria
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.
from faker import Faker
import pandas as pd
fake = Faker()
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 collapse() class from this module. This is a one-line
solution. First, install the module using:
pip install more_itertools
Let’s use to flatten a list.
import more_itertools
print(list(more_itertools.collapse(nested_list)))
Output:
[12, 14, 34, 56, 23, 56, 78]
print(list(more_itertools.collapse(list_tuples)))
Output:
[12, 14, 34, 56, 23, 56, 78, 12, 23, 56]
89 | Factorial of a Number
Below, we write a code that calculates the factorial of a given
number. A factorial of a number is the product of all integers
from 1 to that number. The factorial of 3 is calculated as (1 * 2 *
3), which is 6. The for loop in the function below executes this
calculation. Below, we calculate the factorial of the integer 8.
def factorial_number(n: int):
f = 1
if n < 0:
return 'Negatives numbers have no factorial'
else:
for k in range(1, n + 1):
f = f * k
return f'The factorial of number is {f}'
print(factorial_number(8))
Output:
The factorial of number is 40320
90 | List of Prime Numbers
Given a number, can you write a code that returns a list of all
the prime numbers in its range? For example, 6 should return
[2, 3, 5]. The code below returns a list of all prime numbers in a
given range of a given number. A prime number has two factors:
one and itself. Prime numbers start at 2. Here is the code below:
def prime_numbers() -> list:
# Empty list to append prime numbers
prime_num = []
return prime_num
print(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(f'Total 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)
for cpu, usage in enumerate(cpu_core):
print(f"# {cpu+1} CPU: {usage}%")
Output:
# 1 CPU: 8.8%
# 2 CPU: 6.2%
# 3 CPU: 7.4%
# 4 CPU: 6.2%
You can see from the outputs that the join() method is faster
than concatenation. If you want faster code, use the join()
method. However, you should note that the join() 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 the join() 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 | 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
print(sys.getrecursionlimit())
Output:
1000
import sys
sys.setrecursionlimit(1200)
print(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
You can get information about a country using Python. Python
has a module called countryinfo that returns data about
countries. All you have to do is pass the country name to the
module. Let’s say we want to know about the provinces in
Zambia. We enter the country "Zambia" as the argument, and
then use the provinces method to return all the provinces in
Zambia.
from countryinfo import CountryInfo
country = CountryInfo("Zambia")
print(country.provinces())
Output:
['Central', 'Copperbelt', 'Eastern', 'Luapula',
'Lusaka', 'North-Western', 'Northern', 'Southern',
'Western']
country = CountryInfo("China")
print(country.currencies())
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 10.
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
print(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)
print(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'
# Checking if text contains profanity
print(profanity.contains_profanity(text))
Output:
True
You can also create a custom list of words you want to censor. If
a text contains a word from your list, then it will be censored.
bad_words = [ 'Hate', 'War', 'evil']
censored_text = profanity.censor(text)
print(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 range(len(arr)-1)):
return True
elif all(arr[i] <= arr[i + 1] for i in range(len(arr)-1)):
return True
else:
return False
list1 = [4, 5, 5, 7]
print(check_monotonic(list1))
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 range(len(arr)-1)):
return True
elif all(arr[i] <= arr[i + 1] for i in range(len(arr)-1)):
return True
else:
return False
print(number_factors(8))
Output:
1
2
4
8