Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Saturday 22 June 2024

Different Ways to Print Binary Values as Decimals in Python


Different Ways to Print Binary Values as Decimals in Python
1. Directly using the binary literal
2. Using int function with a binary string
print(int('101', 2))
3. Using format function for binary to decimal conversion
print(int(format(0b101, 'd')))
4. Using f-strings (Python 3.6+)
binary_value = 0b101
5. Using str.format method
binary_value = 0b101

Friday 21 June 2024

Matrix in Python


Rank of Matrix
import numpy as np

x = np.matrix("4,5,16,7;2,-3,2,3;,3,4,5,6;4,7,8,9")
[[ 4  5 16  7]
 [ 2 -3  2  3]
 [ 3  4  5  6]
 [ 4  7  8  9]]
#numpy.linalg.matrix_rank() - return a rank of a matrix
# Syntax: numpy.linalg.matrix_rank(matrix)
rank_matrix = np.linalg.matrix_rank(x)
Determinant of Matrix
import numpy as np

x = np.matrix("4,5,16,7;2,-3,2,3;,3,4,5,6;4,7,8,9")
[[ 4  5 16  7]
 [ 2 -3  2  3]
 [ 3  4  5  6]
 [ 4  7  8  9]]
det_matrix = np.linalg.det(x)
Inverse of a Matrix
inverse formula = A-1 = (1/determinant of A) * adj A

numpy.linalg.inv() - return the multiplicative inverse of a matrix Syntax: numpy.linalg.inv(matrix)

A = np.matrix("3,1,2;3,2,5;6,7,8")
[[3 1 2]
 [3 2 5]
 [6 7 8]]
Inv_matrix = np.linalg.inv(A)
[[ 0.57575758 -0.18181818 -0.03030303]
 [-0.18181818 -0.36363636  0.27272727]
 [-0.27272727  0.45454545 -0.09090909]]

Introduction to Network Automation


Build your subject-matter expertise

This course is part of the Network Automation Engineering Fundamentals Specialization

When you enroll in this course, you'll also be enrolled in this Specialization.

Learn new concepts from industry experts

Gain a foundational understanding of a subject or tool

Develop job-relevant skills with hands-on projects

Earn a shareable career certificate

Join Free: Introduction to Network Automation

There are 3 modules in this course

The Network infrastructure industry has undergone a significant transformation in recent years, with an increasing need for automation due to factors such as a demand for faster and more reliable network deployments. Therefore, there is a growing need for network engineers skilled in automation and programmability.

This course is primarily intended for network engineers, systems engineers, network architects, and managers interested in learning the fundamentals of network automation.

By the end of the course, you will be able to:

- Articulate the role network automation and programmability plays in the context of end-to-end network management and operations.

- Interpret Python scripts with fundamental programming constructs built for network automation use cases.

To be successful in this course, you should be proficient in fundamental network routing & switching technologies, understand the basics of Python programming (3-6 mos exp.), and have some familiarity with Linux.

Network Automation Engineering Fundamentals Specialization


What you'll learn

The issues network automation can solve, building a foundation for further mastery

The basics of NETCONF, RESTCONF, gNMI, and YANG modeling

How to script security topics with Ansible and Python

Join Free: Network Automation Engineering Fundamentals Specialization

Specialization - 5 course series

The Network Automation Engineering Fundamentals Specialization takes mid- to expert-level network engineers through the primary topics of network automation and programmability and prepares them for the NetDevOps environment. This Specialization serves as a well-rounded survey of topics and core skills that a network automation engineer should know to effectively deploy and operate a NetDevOps environment.

Completing this Specialization will help you prepare to operate as a network automation engineer with the skills needed to advance your career.

Applied Learning Project

We do not have any hands-on projects in this specialization curriculum. 

On Completion of this Specialization, you will be prepared to operate as a network automation engineer with the necessary skills needed to advance in your career. This Specialization serves as a well-rounded survey of topics and core skills that a network automation engineer should know to effectively deploy and operate a NetDevOps environment.

Wednesday 19 June 2024

Friday 14 June 2024

Machine Learning with Python: From Beginner to Advanced course syllabus


Module 1: Introduction to Machine Learning

  • Week 1: Overview of Machine Learning

    • What is Machine Learning?
    • Types of Machine Learning: Supervised, Unsupervised, Reinforcement
    • Real-world applications of Machine Learning
    • Setting up Python environment: Anaconda, Jupyter Notebooks, essential libraries (NumPy, pandas, matplotlib, scikit-learn)
  • Week 2: Python for Data Science

    • Python basics: Data types, control flow, functions
    • NumPy for numerical computing
    • pandas for data manipulation
    • Data visualization with matplotlib and seaborn

Module 2: Supervised Learning

  • Week 3: Regression

    • Introduction to regression analysis
    • Simple Linear Regression
    • Multiple Linear Regression
    • Evaluation metrics: Mean Squared Error, R-squared
  • Week 4: Classification

    • Introduction to classification
    • Logistic Regression
    • K-Nearest Neighbors (KNN)
    • Evaluation metrics: Accuracy, Precision, Recall, F1 Score, ROC-AUC
  • Week 5: Advanced Supervised Learning Algorithms

    • Decision Trees
    • Random Forests
    • Gradient Boosting Machines (XGBoost)
    • Support Vector Machines (SVM)

Module 3: Unsupervised Learning

  • Week 6: Clustering

    • Introduction to clustering
    • K-Means Clustering
    • Hierarchical Clustering
    • DBSCAN
  • Week 7: Dimensionality Reduction

    • Introduction to dimensionality reduction
    • Principal Component Analysis (PCA)
    • t-Distributed Stochastic Neighbor Embedding (t-SNE)
    • Singular Value Decomposition (SVD)

Module 4: Reinforcement Learning

  • Week 8: Fundamentals of Reinforcement Learning

    • Introduction to Reinforcement Learning
    • Key concepts: Agents, Environments, Rewards
    • Markov Decision Processes (MDP)
    • Q-Learning
  • Week 9: Deep Reinforcement Learning

    • Deep Q-Networks (DQN)
    • Policy Gradient Methods
    • Applications of Reinforcement Learning

Module 5: Deep Learning

  • Week 10: Introduction to Neural Networks

    • Basics of Neural Networks
    • Activation Functions
    • Training Neural Networks: Forward and Backward Propagation
  • Week 11: Convolutional Neural Networks (CNNs)

    • Introduction to CNNs
    • CNN architectures: LeNet, AlexNet, VGG, ResNet
    • Applications in Image Recognition
  • Week 12: Recurrent Neural Networks (RNNs)

    • Introduction to RNNs
    • Long Short-Term Memory (LSTM) networks
    • Applications in Sequence Prediction

Module 6: Advanced Topics

  • Week 13: Natural Language Processing (NLP)

    • Introduction to NLP
    • Text Preprocessing
    • Sentiment Analysis
    • Topic Modeling
  • Week 14: Model Deployment and Production

    • Saving and loading models
    • Introduction to Flask for API creation
    • Deployment on cloud platforms (AWS, Google Cloud, Heroku)
  • Week 15: Capstone Project

    • Work on a real-world project
    • End-to-end model development: Data collection, preprocessing, model training, evaluation, and deployment
    • Presentation and review

Saturday 8 June 2024

File Chooser using Python


from plyer import filechooser

# Open a file chooser dialog

file_path = filechooser.open_file()

print("Selected file:", file_path)

# Open multiple files chooser dialog

files_path = filechooser.open_file(multiple=True)

print("Selected files:", files_path)

# Save file chooser dialog

save_path = filechooser.save_file()

print("Save file path:", save_path)

Friday 7 June 2024

Python Programming Basics: For Freshers Learn Python Programming Infrastructure and Attend Interviews free pdf


Python Programming Basics

For Freshers Learn Python Programming Infrastructure and Attend Interviews

What You Will Learn

Chapter 1 : Basics

1 Python Introduction

2 Python Variables

Chapter 2 : Data Types

1 Python boolean

2 Python String

3 Python Number

4 Python List

5 Python Tuple

6 Python Dictionary

Chapter 3 : Operators

1 Python Arithmetic Operators

2 Python Bitwise Operators

3 Python Comparison Operators

4 Python Logical Operators

5 Python Ternary Operators

Chapter 4 : Statements

1 Python if

2 Python while

3 Python for loop

4 Python pass

5 Python break

6 Python continue

Chapter 5 : Functions

1 Python function

2 Python Function Recursion

Chapter 6 : Object Oriented

1 Python Modules

2 Python class

3 Python class Inheritance

4 Python Abstract Base Classes

5 Python Operator Overloading

Chapter 7 : Advanced

1 Python File

2 Python Text File

3 Python Exceptions

4 Python Testing

Free PDF: Python Programming Basics: For Freshers Learn Python Programming Infrastructure and Attend Interviews

Hard Copy: Python Programming Basics: For Freshers Learn Python Programming Infrastructure and Attend Interviews

Monday 3 June 2024

Country Details using Python


from countryinfo import CountryInfo

country = CountryInfo(input("Enter Country Name:"))

# Various information about the country

print("Country Name:",


print("Population:", country.population())

print("Area (in square kilometers):", country.area())

print("Region:", country.region())

print("Subregion:", country.subregion())

print("Demonym:", country.demonym())

print("Currency:", country.currencies())

print("Languages:", country.languages())

print("Borders: ", country.borders())

Sunday 2 June 2024

Print Calendar using Python


Let's break down the code and understand what it does step by step.

Code Explanation

Importing the Calendar Module:

from calendar import *

  • This line imports all the functions and classes from the calendar module in Python. The calendar module provides various functions related to calendar operations.

Getting User Input:

year = int(input('Enter Year:'))
  • This line prompts the user to enter a year. The input function takes the user's input as a string, and the int function converts this string to an integer, which is then stored in the variable year.

Printing the Calendar:

print(calendar(year, 2, 1, 8, 4))
  • This line is intended to print the calendar for the given year with specific formatting. 
formatyear(year, w=2, l=1, c=6, m=3):
  • year: The year for which the calendar is to be printed.
  • w: The width of each date column (default is 2).
  • l: The number of lines for each week (default is 1).
  • c: The number of spaces between month columns (default is 6).
  • m: The number of months per row (default is 3).

Friday 31 May 2024

Programmation pour tous (mise en route de Python)



Si vous êtes débutant en programmation et que vous souhaitez apprendre Python, le cours "Programming for Everybody (Getting Started with Python)" de l'Université du Michigan sur Coursera est parfait pour vous. Ce cours, dispensé en français, couvre les bases essentielles de la programmation en Python et est conçu pour ceux qui n'ont aucune expérience préalable en codage.

Contenu du Cours

Le cours comprend :

  • Installation de Python : Guide étape par étape pour installer Python sur votre ordinateur.
  • Écriture de votre premier programme : Introduction aux bases de la syntaxe Python.
  • Utilisation des variables et des fonctions : Apprenez à manipuler les données et à structurer votre code.
  • Boucles et instructions conditionnelles : Découvrez comment contrôler le flux de votre programme.

Structure du Cours

Le cours est structuré de manière à faciliter l'apprentissage avec des vidéos explicatives, des lectures, des quiz interactifs et des devoirs pratiques. Il est conçu pour être suivi à votre propre rythme, ce qui vous permet de l'adapter à votre emploi du temps.

Pourquoi Apprendre Python?

Python est un langage de programmation polyvalent et très populaire. Il est utilisé dans divers domaines tels que le développement web, l'analyse de données, l'intelligence artificielle, et bien plus encore. En apprenant Python, vous ouvrez la porte à de nombreuses opportunités professionnelles.


À la fin du cours, vous aurez la possibilité d'obtenir un certificat partageable qui peut enrichir votre CV et démontrer vos compétences en programmation Python.


Le cours "Programming for Everybody (Getting Started with Python)" est une excellente opportunité pour débuter en programmation. Il offre une introduction complète et accessible à Python, avec le soutien d'une institution prestigieuse comme l'Université du Michigan.

Pour plus d'informations et pour vous inscrire, visitez la page du cours sur Coursera. Bon apprentissage !

rejoindre gratuitement: Programmation pour tous (mise en route de Python)

Saturday 25 May 2024

Download YouTube Videos using Python - pytube



from pytube import YouTube

# YouTube video URL

video_url = ""

# Initialize a YouTube object

yt = YouTube(video_url)

# Select the highest resolution stream

stream = yt.streams.get_highest_resolution()

# Download the video


This Python script uses the pytube library to download a YouTube video.

Let's break down the code:

Importing the necessary module:

from pytube import YouTube
This line imports the YouTube class from the pytube module, which provides functionality to interact with YouTube videos.

Defining the YouTube video URL:

video_url = ""
Here, you specify the URL of the YouTube video you want to download. Replace "" with the URL of the video you want to download.

Initializing a YouTube object:

yt = YouTube(video_url)
This line creates a YouTube object using the specified video URL. This object represents the YouTube video and allows you to access various properties and methods associated with the video.

Selecting the highest resolution stream:

stream = yt.streams.get_highest_resolution()
Here, you retrieve the stream with the highest resolution available for the video. The get_highest_resolution() method returns a Stream object representing the highest resolution stream.

Downloading the video:
Finally, you call the download() method on the Stream object to download the video. This method saves the video file to the current working directory with the default filename.

In summary, this script downloads the YouTube video specified by the video_url variable using the pytube library, selecting the highest resolution available.

Friday 24 May 2024

Python 201: Intermediate Python

Python 201 is the sequel to my first book, Python 101. If you already know the basics of Python and now you want to go to the next level, then this is the book for you! This book is for intermediate level Python programmers only. There won't be any beginner chapters here. This book is based on Python 3.

The book will be broken up into five parts. Here's how:

Part I - Intermediate Modules

Chapter 1 - The argparse module

Chapter 2 - The collections module

Chapter 3 - The contextlib module (Context Managers)

Chapter 4 - The functools module (Function overloading, caching, etc)

Chapter 5 - All about imports

Chapter 6 - The importlib module

Chapter 7 - Iterators and Generators

Chapter 8 - The itertools module

Chapter 9 - The re module (An Intro to Regex in Python)

Chapter 10 - The typing module (Type Hinting)

Part II - Odds and Ends

Chapter 11 - map, filter and more

Chapter 12 - unicode

Chapter 13 - benchmarking

Chapter 14 - encryption

Chapter 15 - Connecting to databases

Chapter 16 - super

Chapter 17 - descriptors

Chapter 18 - Scope (local, global and the new non_local)

Part III - Web

Chapter 19 - Web scraping

Chapter 20 - Working with web APIs

Chapter 21 - ftplib

Chapter 22 - urllib

Part IV - Testing

Chapter 23 - Doctest

Chapter 24 - unittest

Chapter 25 - mock

Chapter 26 -

Part V - Concurrency

Chapter 27 - The asyncio module

Chapter 28 - The threading module

Chapter 29 - The multiprocessing module

Chapter 30 - The concurrent.futures module

Join the course: Python 201: Intermediate Python

Thursday 23 May 2024

Convert to mathematical symbols using Python 🧵


import math
import latexify
def quadratic_roots(a, b, c):
    discriminant = b ** 2 - 4 * a * c
    root1 = (-b + math.sqrt(discriminant)) / (2 * a)
    root2 = (-b - math.sqrt(discriminant)) / (2 * a)
    return root1, root2
import math
import latexify
def pythagorean_theorem(a, b):
    return math.sqrt(a ** 2 + b ** 2)
import math
import latexify
def compound_interest(P, r, n, t):
    return P * (1 + r/n) ** (n*t)

import math
import latexify
def distance(x1, y1, x2, y2):
  return math.sqrt((x2-x1)**2 + (y2-y1)**2)
import math
import latexify
def factorial(n):
  if n == 0:
    return 1
  elif n == 1:
    return 1
    return n * factorial(n-1)

Tuesday 21 May 2024

Pdf To Audio using Python


# Importing necessary libraries

import PyPDF2

import pyttsx3

# Prompt user for the PDF file name

pdf_filename = input("Enter the PDF file name (including extension): ").strip()

# Open the PDF file


    with open(pdf_filename, 'rb') as pdf_file:

        # Create a PdfFileReader object

        pdf_reader = PyPDF2.PdfReader(pdf_file)


        # Get an engine instance for the speech synthesis

        speak = pyttsx3.init()        

        # Iterate through each page and read the text

        for page_num in range(len(pdf_reader.pages)):

            page = pdf_reader.pages[page_num]

            text = page.extract_text()

            if text:



        # Stop the speech engine


        print("Audiobook creation completed.")

except FileNotFoundError:

    print("The specified file was not found.")

except Exception as e:

    print(f"An error occurred: {e}")


This script segment accomplishes several tasks:

Importing Necessary Libraries:

PyPDF2: This library is used to work with PDF files, allowing us to read the content of PDF documents.
pyttsx3: This library is used for text-to-speech conversion, enabling us to convert the text extracted from the PDF into spoken words.
Prompting User for PDF File Name:

The input() function is used to prompt the user to enter the name of the PDF file, including its extension (e.g., example.pdf).
The entered file name is stored in the variable pdf_filename.
Opening the PDF File:

The open() function is used to open the PDF file specified by the user. The file is opened in binary read mode ('rb').
This operation is wrapped in a try block to handle possible exceptions, such as the file not being found (FileNotFoundError) or other unexpected errors (Exception).
Reading PDF Content and Converting to Speech:

If the PDF file is successfully opened, a PdfReader object named pdf_reader is created using PyPDF2. This object is used to read the content of the PDF document.
An instance of the text-to-speech engine (speak) is initialized using pyttsx3.init().
The script iterates through each page of the PDF using a for loop and the range(len(pdf_reader.pages)) construct. For each page:
The text content is extracted from the page using page.extract_text().
If the extracted text is not empty, it is passed to the text-to-speech engine to be spoken aloud using speak.say(text) and speak.runAndWait().
After processing all pages, the text-to-speech engine is stopped using speak.stop().
Error Handling:

If the specified PDF file is not found (FileNotFoundError), the script prints a message indicating that the file was not found.
If any other unexpected error occurs during the execution of the script (Exception), the error message is printed.
Completion Message:

If the script executes successfully without encountering any errors, a message indicating the completion of audiobook creation is printed.
Overall, this script segment enables the user to specify a PDF file, reads its content, converts the text to speech, and creates an audiobook from the PDF content.

Monday 20 May 2024

Box and Whisker plot using Python Libraries

Step 1: Install Necessary Libraries

First, make sure you have matplotlib and seaborn installed. You can install them using pip:

pip install matplotlib seaborn

Step 2: Import Libraries

Next, import the necessary libraries in your Python script or notebook.

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

Step 3: Create Sample Data

Create some sample data to plot. This can be any dataset you have, but for demonstration purposes, we will create a simple dataset using NumPy.

# Generate sample data
data = [np.random.normal(0, std, 100) for std in range(1, 5)]

Step 4: Create the Box and Whisker Plot

Using matplotlib and seaborn, you can create a basic Box and Whisker plot.

# Create a boxplot
plt.figure(figsize=(10, 6))
plt.boxplot(data, patch_artist=True)

# Add title and labels
plt.title('Box and Whisker Plot')

# Show plot

Step 5: Enhance the Plot with Seaborn

For more advanced styling, you can use seaborn, which provides more aesthetic options.

# Set the style of the visualization


# Create a boxplot with seaborn

plt.figure(figsize=(10, 6))


# Add title and labels

plt.title('Box and Whisker Plot')



# Show plot

Thursday 16 May 2024

Interesting facts about Dictionaries

 Dictionary Methods

Dictionaries come with several handy methods such as setdefault, update, pop, popitem, and clear.

my_dict = {'name': 'Alice', 'age': 25}

# setdefault
my_dict.setdefault('city', 'Unknown')

# update
my_dict.update({'age': 26, 'city': 'New York'})

# pop
age = my_dict.pop('age')
print(age)  # Output: 26

# popitem
item = my_dict.popitem()

# clear
{'name': 'Alice', 'age': 25, 'city': 'Unknown'}
{'name': 'Alice', 'age': 26, 'city': 'New York'}
{'name': 'Alice', 'city': 'New York'}
('city', 'New York')
{'name': 'Alice'}

Ordered Dictionaries

As of Python 3.7, dictionaries maintain insertion order by default. The OrderedDict from the collections module was used for this purpose in earlier versions.

my_dict = {'first': 1, 'second': 2, 'third': 3}
{'first': 1, 'second': 2, 'third': 3}

Merging Dictionaries

Starting with Python 3.9, you can use the | operator to merge dictionaries.

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = dict1 | dict2
{'a': 1, 'b': 3, 'c': 4}
Dictionary Views
The keys, values, and items methods return dictionary view objects, which are dynamic and reflect changes in the dictionary.

my_dict = {'name': 'Alice', 'age': 25}
keys_view = my_dict.keys()
my_dict['city'] = 'New York'
dict_keys(['name', 'age'])
dict_keys(['name', 'age', 'city'])

Default Values with get and defaultdict

Using the get method, you can provide a default value if the key is not found.

my_dict = {'name': 'Alice'}
print(my_dict.get('age', 'Not Found'))  
Not Found
With defaultdict from the collections module, you can provide default values for missing keys.

from collections import defaultdict

dd = defaultdict(int)
dd['a'] += 1
defaultdict(<class 'int'>, {'a': 1})

Dictionary Comprehensions

Just like list comprehensions, you can create dictionaries using dictionary comprehensions.

squares = {x: x*x for x in range(6)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Iterating Through Dictionaries

You can iterate through keys, values, or key-value pairs in a dictionary.

my_dict = {'name': 'Alice', 'age': 25}
for key in my_dict:

for value in my_dict.values():

for key, value in my_dict.items():
    print(key, value)
name Alice
age 25

Keys Must Be Immutable and Unique

The keys in a dictionary must be immutable types (like strings, numbers, or tuples) and must be unique.

my_dict = {(1, 2): 'tuple key', 'name': 'Alice', 3.14: 'pi'}
{(1, 2): 'tuple key', 'name': 'Alice', 3.14: 'pi'}

Efficient Lookup Time

Dictionaries have average O(1) time complexity for lookups, insertions, and deletions due to their underlying hash table implementation.

my_dict = {'a': 1, 'b': 2, 'c': 3}

Dynamic and Mutable

Dictionaries are mutable, which means you can change their content without changing their identity.

my_dict = {'name': 'Alice', 'age': 25}
my_dict['age'] = 26
my_dict['city'] = 'New York'
{'name': 'Alice', 'age': 26, 'city': 'New York'}

Monday 13 May 2024

Python Libraries for Financial Analysis and Portfolio Management


import statsmodels.api as sm
import numpy as np

# Generate some sample data
x = np.random.rand(100)
y = 2 * x + np.random.randn(100)

# Fit a linear regression model
model = sm.OLS(y, sm.add_constant(x)).fit()

print("Regression coefficients:", model.params)
print("R-squared:", model.rsquared) 
import pandas as pd

# Create a simple DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 35],
        'Salary': [50000, 60000, 70000]}
df = pd.DataFrame(data)

# Perform data analysis
print("DataFrame head:")
print("\nAverage salary:", df['Salary'].mean()) 
import numpy as np

# Create a simple array
arr = np.array([1, 2, 3, 4, 5])

# Perform numerical operations
print("Sum:", np.sum(arr))
print("Mean:", np.mean(arr))
print("Standard deviation:", np.std(arr)) 
from ibapi.client import EClient
from ibapi.wrapper import EWrapper

class MyWrapper(EWrapper):
    def __init__(self):

class MyClient(EClient):
    def __init__(self, wrapper):
        EClient.__init__(self, wrapper)

app = MyClient(MyWrapper())
app.connect("", 7497, clientId=1) 
import numpy as np
from scipy import optimize

# Define a simple objective function
def objective(x):
    return x**2 + 10*np.sin(x)

# Optimize the objective function
result = optimize.minimize(objective, x0=0)

print("Minimum value found at:", result.x)
print("Objective function value at minimum:", 
from riskfolio.Portfolio import Portfolio

# Create a simple portfolio
data = {'Asset1': [0.05, 0.1, 0.15],
        'Asset2': [0.08, 0.12, 0.18],
        'Asset3': [0.06, 0.11, 0.14]}
portfolio = Portfolio(returns=data)

# Perform portfolio optimization

print("Optimal weights:", portfolio.w)
print("Expected return:",
print("Volatility:", portfolio.sigma) 

Saturday 11 May 2024

Happy Mother's Day!



import pyfiglet

from termcolor import colored

import random

def get_random_font_style():

    # List of available Figlet font styles

    font_styles = pyfiglet.FigletFont.getFonts() 

    # Choose a random font style from the list

    return random.choice(font_styles)

def get_random_color():

    # List of available colors

    colors = ['red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']

    # Choose a random color from the list

    return random.choice(colors)

def wish_mothers_day():

    # Get a random font style and color

    random_font_style = get_random_font_style()

    random_color = get_random_color()

    # Create a Figlet font object with the random style

    font = pyfiglet.Figlet(font=random_font_style)

    # Print the decorative greeting in the chosen color

    print(colored(font.renderText("Happy Mother's Day!"), random_color))


Solution and Explanation:

This code generates a Mother's Day wish with a randomly selected font style and color using the pyfiglet and termcolor libraries in Python. Here's a breakdown of what each part of the code does:

import pyfiglet: Imports the pyfiglet library, which is used to create ASCII art text.

from termcolor import colored: Imports the colored function from the termcolor library, which is used to add color to text in the terminal.

import random: Imports the random module, which is used to generate random font styles and colors.

get_random_font_style(): Defines a function that returns a random font style chosen from the available Figlet font styles provided by pyfiglet.

get_random_color(): Defines a function that returns a random color chosen from a predefined list of colors.

wish_mothers_day(): Defines the main function responsible for printing the Mother's Day wish. Inside this function:

random_font_style is assigned a random font style using get_random_font_style().
random_color is assigned a random color using get_random_color().
A Figlet font object is created using the random font style.
The text "Happy Mother's Day!" is rendered using the chosen font style and colored with the chosen color using the colored function.
The rendered text is printed to the console.
wish_mothers_day(): Finally, the wish_mothers_day() function is called to generate and print the Mother's Day wish with a random font style and color.

This code allows you to produce colorful and decorative Mother's Day wishes each time it's run, adding a touch of randomness and visual appeal to the message.

Popular Posts


AI (28) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (121) C (77) C# (12) C++ (82) Course (66) Coursera (184) Cybersecurity (24) data management (11) Data Science (99) Data Strucures (7) Deep Learning (11) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Pandas (3) PHP (20) Projects (29) Python (791) Python Coding Challenge (268) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (41) UX Research (1) web application (8)


Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses