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

Monday 8 April 2024

Plant Leaf using Python

 

import numpy as np

import matplotlib.pyplot as plt

t = np.linspace(0, 39*np.pi/2, 1000)

x = t * np.cos(t)**3

y = 9*t * np.sqrt(np.abs(np.cos(t))) + t * np.sin(0.2*t) * np.cos(4*t)

plt.plot(x, y, c="green")

plt.show()

#clcoding.com

Explanation: 

This code snippet is written in Python and utilizes two popular libraries for numerical computing and visualization: NumPy and Matplotlib.

Here's a breakdown of what each part of the code does:

import numpy as np: This line imports the NumPy library and allows you to use its functionalities in your code. NumPy is a powerful library for numerical computations in Python, providing support for arrays, matrices, and mathematical functions.

import matplotlib.pyplot as plt: This line imports the pyplot module from the Matplotlib library, which is used for creating static, animated, and interactive visualizations in Python. It's typically imported with the alias plt for convenience.

t = np.linspace(0, 39*np.pi/2, 1000): This line generates an array t of 1000 equally spaced values ranging from 0 to 
39
2
2
39π
 . np.linspace() is a NumPy function that generates linearly spaced numbers.

x = t * np.cos(t)**3: This line computes the x-coordinates of the points on the plot. It utilizes NumPy's array operations to compute the expression 
×
cos
(
)
3
t×cos(t) 
3
 .

y = 9*t * np.sqrt(np.abs(np.cos(t))) + t * np.sin(0.2*t) * np.cos(4*t): This line computes the y-coordinates of the points on the plot. It's a more complex expression involving trigonometric functions and mathematical operations.

plt.plot(x, y, c="green"): This line plots the x and y coordinates as a line plot. The c="green" argument specifies the color of the line as green.

plt.show(): This line displays the plot on the screen. It's necessary to call this function to actually see the plot.

Overall, this code generates a plot of a parametric curve defined by the equations for x and y. The resulting plot will depict the curve in green.



import numpy as np
import matplotlib.pyplot as plt

# Define the parameter t
t = np.linspace(0, 39*np.pi/2, 1000)

# Define the equations for x and y
x = t * np.cos(t)**3
y = 9*t * np.sqrt(np.abs(np.cos(t))) + t * np.sin(0.2*t) * np.cos(4*t)

# Define the segment indices and corresponding colors
segments = [
    (0, 200, 'orange'),  # Green segment
    (200, 600, 'magenta'),   # Red segment
    (600, 1000, 'red')  # Orange segment
]

# Plot each segment separately with the corresponding color
for start, end, color in segments:
    plt.plot(x[start:end], y[start:end], c=color)

plt.show()
#clcoding.com 









Playing a YouTube Video using Python

 

import pywhatkit

# Using Exception Handling to avoid unprecedented errors

try:

    # Ask the user to input the song name

    song = input("Enter Song Name: ")

    # Play a YouTube video corresponding to the search term entered by the user

    pywhatkit.playonyt(song)    

    # Print a success message if the video is played successfully

    print("Successfully Played!") 

except:

    # Handle exceptions and print an error message if any unexpected error occurs

    print("An Unexpected Error!")


Explanation:

Importing the Module: import pywhatkit imports the pywhatkit module, which provides various functionalities, including playing YouTube videos.


Exception Handling (try-except): The code is wrapped in a try block, which allows Python to attempt the code within it. If an error occurs during the execution of the code inside the try block, Python will stop executing that block and jump to the except block.


User Input: Inside the try block, the input() function prompts the user to enter the name of the song they want to play on YouTube. The entered song name is stored in the variable song.


Playing YouTube Video: The pywhatkit.playonyt() function is called with the song variable as an argument. This function opens a web browser and plays the YouTube video corresponding to the search term entered by the user.


Success Message: If the video is played successfully without any errors, the code inside the try block will execute completely, and the success message "Successfully Played!" will be printed.


Exception Handling (except): If any unexpected error occurs during the execution of the code inside the try block, Python will jump to the except block and execute the code within it. In this case, it simply prints the error message "An Unexpected Error!". This ensures that the program does not crash abruptly if an error occurs during video playback.


Overall, this code allows users to input the name of a song, and it plays the corresponding YouTube video while handling any unexpected errors that may occur during execution.

Sending a WhatsApp Message using Python

 

# importing the module

import pywhatkit


# using Exception Handling to avoid unprecedented errors

try:


# sending message to receiver using pywhatkit

    pywhatkit.sendwhatmsg("+919767292502","Hello Python",21, 23)

    print("Successfully Sent!")

except:


# handling exception and printing error message

    print("An Unexpected Error!")

Here's what each part does:

Importing the Module: import pywhatkit imports the pywhatkit module, which provides various functionalities, including sending WhatsApp messages.

Exception Handling (try-except): The code is wrapped in a try block, which allows Python to attempt the code within it. If an error occurs during the execution of the code inside the try block, Python will stop executing that block and jump to the except block.

Sending WhatsApp Message: Inside the try block, the pywhatkit.sendwhatmsg() function is called to send a WhatsApp message. It takes four arguments: the recipient's phone number (including the country code), the message content, the hour of the day (in 24-hour format) at which the message will be sent, and the minute of the hour.

Success Message: If the message is sent successfully without any errors, the code inside the try block will execute completely, and the success message "Successfully Sent!" will be printed.

Exception Handling (except): If any unexpected error occurs during the execution of the code inside the try block, Python will jump to the except block and execute the code within it. In this case, it simply prints the error message "An Unexpected Error!". This ensures that the program does not crash abruptly if an error occurs during message sending.

Saturday 6 April 2024

Wednesday 3 April 2024

Convert PDF files using Python


from gtts import gTTS
from PyPDF2 import PdfReader

def pdf_to_text(pdf_file):
    text = ""
    with open(pdf_file, 'rb') as f:
        reader = PdfReader(f)
        for page_num in range(len(reader.pages)):
            page = reader.pages[page_num]
            text += page.extract_text()
    return text

def text_to_audio(text, output_file):
    tts = gTTS(text)
    tts.save(output_file)

# Example usage:
pdf_file = "clcoding.pdf"
output_audio_file = "clcoding_audio.mp3"

text = pdf_to_text(pdf_file)
text_to_audio(text, output_audio_file)

#clcoding.com

Explanation: 

This code snippet is a Python script that converts text from a PDF file to an audio file using the Google Text-to-Speech (gTTS) library (gTTS) and the PyPDF2 library (PdfReader).

Here's a breakdown of what each part of the code does:

Importing Required Libraries:

from gtts import gTTS: This imports the gTTS class from the gtts module, which allows us to convert text to speech using Google Text-to-Speech.
from PyPDF2 import PdfReader: This imports the PdfReader class from the PyPDF2 library, which is used to read PDF files.
pdf_to_text(pdf_file) Function:

This function takes a PDF file path (pdf_file) as input.
It opens the PDF file in binary mode and creates a PdfReader object to read the content of the PDF.
It iterates through each page of the PDF (reader.pages) and extracts text from each page using the extract_text() method.
It concatenates all the extracted text from each page into a single string (text).
Finally, it returns the concatenated text.
text_to_audio(text, output_file) Function:

This function takes two arguments: the text to convert to audio (text) and the file path where the audio will be saved (output_file).
It creates a gTTS object (tts) by passing the input text.
It saves the generated audio file to the specified output file path.
Example Usage:

It defines the input PDF file (pdf_file) as "clcoding.pdf".
It defines the output audio file path (output_audio_file) as "clcoding_audio.mp3".
It calls the pdf_to_text() function to extract text from the PDF file.
It calls the text_to_audio() function to convert the extracted text to audio and save it to the specified output file.
The comment #clcoding.com is unrelated to the code and appears to be a note or reference to a website.

This script essentially converts the text content of a PDF file into audio, which could be useful for tasks such as creating audiobooks, generating voiceovers, or assisting users with reading disabilities.

import os
from PyPDF2 import PdfReader
from pdf2image import convert_from_path

def pdf_to_images(pdf_file, output_dir):
    images = []
    with open(pdf_file, 'rb') as f:
        reader = PdfReader(f)
        for page_num, _ in enumerate(reader.pages):
            # Convert each PDF page to image
            img_path = os.path.join(output_dir, f"page_{page_num}.png")
            images.append(img_path)
    return images

# Example usage:
pdf_file = "clcoding.pdf"
output_dir = "output_images"

if not os.path.exists(output_dir):
    os.makedirs(output_dir)

pdf_to_images(pdf_file, output_dir)

#clcoding.com

Explanation: 

This Python script converts each page of a PDF file into an image format (PNG) using the PyPDF2 library to read the PDF and the pdf2image library to perform the conversion.

Here's a breakdown of each part of the code:

Importing Required Libraries:

import os: This imports the os module, which provides functions for interacting with the operating system, such as creating directories.
from PyPDF2 import PdfReader: This imports the PdfReader class from the PyPDF2 library, which is used to read PDF files.
from pdf2image import convert_from_path: This imports the convert_from_path function from the pdf2image library, which is used to convert PDF pages to images.
pdf_to_images(pdf_file, output_dir) Function:

This function takes two arguments: the path to the input PDF file (pdf_file) and the directory where the output images will be saved (output_dir).
It initializes an empty list called images to store the file paths of the converted images.
It opens the PDF file in binary mode ('rb') using a context manager (with open(...) as f) and creates a PdfReader object (reader) to read the content of the PDF.
It iterates through each page of the PDF (reader.pages) using enumerate to get both the page number and the page object.
For each page, it generates a file path for the corresponding image in the output directory (output_dir) using os.path.join and appends it to the images list.
Finally, it returns the list of image file paths.
Example Usage:

It defines the input PDF file (pdf_file) as "clcoding.pdf".
It defines the output directory (output_dir) as "output_images".
It checks if the output directory does not exist (if not os.path.exists(output_dir)), and if not, it creates the directory using os.makedirs(output_dir).
It calls the pdf_to_images() function to convert the PDF pages to images and stores the list of image file paths.
The comment #clcoding.com is unrelated to the code and appears to be a note or reference to a website.

This script can be useful for tasks such as converting PDF pages to images for further processing or display, such as in document management systems, image processing pipelines, or for creating thumbnails of PDF documents.

import os
from PyPDF2 import PdfReader
import docx

def pdf_to_text():
    pdf_file = "clcoding.pdf"
    text = ""
    with open(pdf_file, 'rb') as f:
        reader = PdfReader(f)
        for page_num in range(len(reader.pages)):
            page_text = reader.pages[page_num].extract_text()
            text += page_text
    return text

def pdf_to_docx(output_file):
    text = pdf_to_text()
    doc = docx.Document()
    doc.add_paragraph(text)
    doc.save(output_file)

# Example usage:
output_docx_file = "output_docx.docx"

pdf_to_docx(output_docx_file)

#clcoding.com

Explanation:

This Python script converts the text content of a PDF file ("clcoding.pdf") into a Microsoft Word document (.docx) using the PyPDF2 library to extract text from the PDF and the python-docx library to create and save the Word document.

Here's a breakdown of each part of the code:

Importing Required Libraries:

import os: This imports the os module, which provides functions for interacting with the operating system, such as creating directories or checking file paths.
from PyPDF2 import PdfReader: This imports the PdfReader class from the PyPDF2 library, which is used to read PDF files.
import docx: This imports the docx module, which is part of the python-docx library, used for creating and manipulating Word documents.
pdf_to_text() Function:

This function reads the text content of the PDF file ("clcoding.pdf").
It initializes an empty string called text to store the extracted text.
It opens the PDF file in binary mode ('rb') using a context manager (with open(...) as f) and creates a PdfReader object (reader) to read the content of the PDF.
It iterates through each page of the PDF (reader.pages) using range(len(reader.pages)) to get the page number.
For each page, it extracts the text using the extract_text() method of the page object and appends it to the text string.
Finally, it returns the concatenated text.
pdf_to_docx(output_file) Function:

This function converts the extracted text from the PDF to a Word document.
It calls the pdf_to_text() function to get the text content of the PDF.
It creates a new docx.Document() object (doc) to represent the Word document.
It adds a paragraph containing the extracted text to the document using the add_paragraph() method.
It saves the document to the specified output file path using the save() method.
Example Usage:

It defines the output Word document file path (output_docx_file) as "output_docx.docx".
It calls the pdf_to_docx() function to convert the PDF text content to a Word document and save it to the specified output file.
The comment #clcoding.com is unrelated to the code and appears to be a note or reference to a website.

This script is useful for converting the text content of a PDF file to a Word document, which can be helpful for further editing or formatting. Make sure you have the necessary libraries installed (PyPDF2 and python-docx).

 import os
from PyPDF2 import PdfReader
import pandas as pd

def pdf_to_text():
    pdf_file = "clcoding.pdf"
    text = ""
    with open(pdf_file, 'rb') as f:
        reader = PdfReader(f)
        for page_num in range(len(reader.pages)):
            page_text = reader.pages[page_num].extract_text()
            text += page_text
    return text

def pdf_to_excel(output_file):
    text = pdf_to_text()
    lines = text.split('\n')
    df = pd.DataFrame(lines)
    df.to_excel(output_file, index=False, header=False)

# Example usage:
output_excel_file = "output_excel.xlsx"

pdf_to_excel(output_excel_file)

#clcoding.com

Explanation:

This Python script reads the text content of a PDF file ("clcoding.pdf") and then converts it into an Excel file (.xlsx) using the Pandas library. Here's a breakdown of each part of the code:

Importing Required Libraries:

import os: This imports the os module, which provides functions for interacting with the operating system, such as creating directories or checking file paths.
from PyPDF2 import PdfReader: This imports the PdfReader class from the PyPDF2 library, which is used to read PDF files.
import pandas as pd: This imports the Pandas library, often used for data manipulation and analysis.
pdf_to_text() Function:

This function reads the text content of the PDF file ("clcoding.pdf").
It initializes an empty string called text to store the extracted text.
It opens the PDF file in binary mode ('rb') using a context manager (with open(...) as f) and creates a PdfReader object (reader) to read the content of the PDF.
It iterates through each page of the PDF (reader.pages) using range(len(reader.pages)) to get the page number.
For each page, it extracts the text using the extract_text() method of the page object and appends it to the text string.
Finally, it returns the concatenated text.
pdf_to_excel(output_file) Function:

This function converts the extracted text from the PDF to an Excel file.
It calls the pdf_to_text() function to get the text content of the PDF.
It splits the text into lines using the newline character ('\n') and creates a list of lines.
It creates a Pandas DataFrame (df) from the list of lines.
It saves the DataFrame to an Excel file specified by the output_file parameter using the to_excel() method, without including the index or header.
Example Usage:

It defines the output Excel file path (output_excel_file) as "output_excel.xlsx".
It calls the pdf_to_excel() function to convert the PDF text content to an Excel file and save it to the specified output file.
The comment #clcoding.com is unrelated to the code and appears to be a note or reference to a website.

This script can be useful for extracting text data from PDF files and converting it into a structured format like an Excel spreadsheet for further analysis or manipulation. Make sure you have the necessary libraries installed (PyPDF2 and pandas).



import os
from PyPDF2 import PdfReader
from pptx import Presentation

def pdf_to_text():
    pdf_file = "clcoding.pdf"  # Using "clcoding.pdf"
    text = ""
    with open(pdf_file, 'rb') as f:
        reader = PdfReader(f)
        for page_num in range(len(reader.pages)):
            page_text = reader.pages[page_num].extract_text()
            text += page_text
    return text

def pdf_to_ppt(output_file):
    text = pdf_to_text()
    prs = Presentation()
    slides = text.split('\n\n')
    for slide_content in slides:
        slide = prs.slides.add_slide(prs.slide_layouts[1])
        slide.shapes.title.text = slide_content
    prs.save(output_file)

# Example usage:
output_ppt_file = "output_ppt.pptx"

pdf_to_ppt(output_ppt_file)

#clcoding.com

Explanation:

This Python script converts the text content of a PDF file ("clcoding.pdf") into a PowerPoint presentation (.pptx) using the PyPDF2 library to extract text from the PDF and the python-pptx library to create and save the PowerPoint presentation.

Here's a breakdown of each part of the code:

Importing Required Libraries:

import os: This imports the os module, which provides functions for interacting with the operating system, such as creating directories or checking file paths.
from PyPDF2 import PdfReader: This imports the PdfReader class from the PyPDF2 library, which is used to read PDF files.
from pptx import Presentation: This imports the Presentation class from the pptx module, which is part of the python-pptx library used for creating and manipulating PowerPoint presentations.
pdf_to_text() Function:

This function reads the text content of the PDF file ("clcoding.pdf").
It initializes an empty string called text to store the extracted text.
It opens the PDF file in binary mode ('rb') using a context manager (with open(...) as f) and creates a PdfReader object (reader) to read the content of the PDF.
It iterates through each page of the PDF (reader.pages) using range(len(reader.pages)) to get the page number.
For each page, it extracts the text using the extract_text() method of the page object and appends it to the text string.
Finally, it returns the concatenated text.
pdf_to_ppt(output_file) Function:

This function converts the extracted text from the PDF to a PowerPoint presentation.
It calls the pdf_to_text() function to get the text content of the PDF.
It creates a new Presentation() object (prs) to represent the PowerPoint presentation.
It splits the text into slides based on double newline characters ('\n\n').
For each slide content, it adds a new slide to the presentation using the add_slide() method, specifying the layout of the slide.
It sets the title of each slide to the slide content using the shapes.title.text property.
Finally, it saves the presentation to the specified output file path using the save() method.
Example Usage:

It defines the output PowerPoint file path (output_ppt_file) as "output_ppt.pptx".
It calls the pdf_to_ppt() function to convert the PDF text content to a PowerPoint presentation and save it to the specified output file.
The comment #clcoding.com is unrelated to the code and appears to be a note or reference to a website.

This script can be useful for converting the text content of a PDF file into a structured format like a PowerPoint presentation, which can be helpful for presentations or sharing information in a visually appealing format. Make sure you have the necessary libraries installed (PyPDF2 and python-pptx).

Tuesday 2 April 2024

Doughnut Plot using Python

 

import plotly.graph_objects as go


# Sample data

labels = ['A', 'B', 'C', 'D']

values = [20, 30, 40, 10]

colors = ['#FFA07A', '#FFD700', '#6495ED', '#ADFF2F']


# Create doughnut plot

fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=.5, marker=dict(colors=colors))])

fig.update_traces(textinfo='percent+label', textfont_size=14, hoverinfo='label+percent')

fig.update_layout(title_text="Customized Doughnut Plot", showlegend=False)


# Show plot

fig.show()


#clcoding.com


import matplotlib.pyplot as plt


# Sample data

labels = ['Category A', 'Category B', 'Category C', 'Category D']

sizes = [20, 30, 40, 10]

explode = (0, 0.1, 0, 0)  # "explode" the 2nd slice


# Create doughnut plot

fig, ax = plt.subplots()

ax.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', startangle=90, shadow=True, colors=plt.cm.tab20.colors)

ax.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle


# Draw a white circle at the center to create a doughnut plot

centre_circle = plt.Circle((0, 0), 0.7, color='white', fc='white', linewidth=1.25)

fig.gca().add_artist(centre_circle)


# Add a title

plt.title('Doughnut Plot with Exploded Segment and Shadow Effect')


# Show plot

plt.show()


#clcoding.com



import plotly.graph_objects as go


# Sample data

labels = ['A', 'B', 'C', 'D']

values = [20, 30, 40, 10]


# Create doughnut plot

fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=.5)])

fig.update_layout(title_text="Doughnut Plot")


# Show plot

fig.show()


#clcoding.com



import matplotlib.pyplot as plt


# Sample data

labels = ['Category A', 'Category B', 'Category C', 'Category D']

sizes = [20, 30, 40, 10]


# Create doughnut plot

fig, ax = plt.subplots()

ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, colors=plt.cm.tab20.colors)

ax.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle


# Draw a white circle at the center to create a doughnut plot

centre_circle = plt.Circle((0, 0), 0.7, color='white', fc='white', linewidth=1.25)

fig.gca().add_artist(centre_circle)


# Add a title

plt.title('Doughnut Plot')


# Show plot

plt.show()


#clcoding.com

Sunday 31 March 2024

Happy Easter wishes using Python

 


import pyfiglet

from termcolor import colored


def wish_happy_easter():

    # Creating a colorful Happy Easter message using pyfiglet and termcolor

    easter_message = pyfiglet.figlet_format("Happy Easter!")

    colored_message = colored(easter_message, color='yellow', attrs=['bold'])

    

    # Additional colorful text

    additional_text = colored("\nWishing you a joyful and blessed Easter !")

    

    print(colored_message + additional_text)


wish_happy_easter()


#clcoding.com

Thursday 28 March 2024

pytube library for downloading YouTube videos

 

# Get a specific stream
stream = yt.streams.get_by_itag(22)  # Example: iTAG for 720p MP4

# Download the stream
stream.download()

#clcoding.com 

# Get the best audio stream
audio_stream = yt.streams.get_audio_only()

# Download the audio
audio_stream.download()

#clcoding.com 





# Get streams with only audio
audio_streams = yt.streams.filter(only_audio=True)

# Get streams with only video
video_streams = yt.streams.filter(only_video=True)

# Get streams with a specific resolution
hd_streams = yt.streams.filter(res="720p")

#clcoding.com 

# Get all available streams

streams = yt.streams.all()


# Print available streams

for stream in streams:

    print(stream)


#clcoding.com 

# Get streams with only audio

audio_streams = yt.streams.filter(only_audio=True)


# Get streams with only video

video_streams = yt.streams.filter(only_video=True)


# Get streams with a specific resolution

hd_streams = yt.streams.filter(res="720p")


#clcoding.com 



# Title of the video

print("Title:", yt.title)


# Description of the video

print("Description:", yt.description)


# Thumbnail URL of the video

print("Thumbnail URL:", yt.thumbnail_url)


# Video length in seconds

print("Length (seconds):", yt.length)


# Number of views

print("Views:", yt.views)


#clcoding.com 




from pytube import YouTube


# YouTube video URL

video_url = 'https://www.youtube.com/watch?v=qMNKy_4opeE'


# Initialize a YouTube object with the video URL

yt = YouTube(video_url)


# Get the highest resolution stream

stream = yt.streams.get_highest_resolution()


# Download the video

stream.download()


print("Download completed!")


#clcoding.com 

Tuesday 26 March 2024

How to install modules without pip ?

 Installing Python modules without using pip can be done manually by downloading the module's source code or distribution package and then installing it using Python's setup tools. Here's a basic guide on how to do it:

Download the module: Go to the official website or repository of the module you want to install and download the source code or distribution package (usually in a .tar.gz or .zip format).

Extract the package: Extract the downloaded package to a directory on your computer.

Navigate to the package directory: Open a terminal or command prompt and navigate to the directory where you extracted the package.

Install the module: Run the following command to install the module using Python's setup tools:

python setup.py install

If you have multiple versions of Python installed, you may need to specify the Python version explicitly, for example:

python3 setup.py install

This command will compile and install the module into your Python environment.

Verify installation: After installation, you can verify if the module is installed correctly by trying to import it in a Python script or interpreter.

Keep in mind that installing modules manually without pip may require additional dependencies and manual handling of version compatibility. It's generally recommended to use pip whenever possible, as it handles dependency resolution and installation automatically. However, manual installation can be useful in cases where pip is not available or suitable for some reason.







Sunday 24 March 2024

Happy Holi wishes using Python

 



from colorama import Fore

import pyfiglet

font = pyfiglet.figlet_format('Happy  Holi')

print(Fore.MAGENTA+font)


#clcoding.com




import pyfiglet

from termcolor import colored


def wish_happy_holi():

    # Happy Holi message using pyfiglet and termcolor

    holi_message = pyfiglet.figlet_format("Happy Holi!")

    colored_message = colored(holi_message, color='red')

    print(colored_message)


wish_happy_holi()

Saturday 23 March 2024

GeoPy Library in Python

 

from geopy.geocoders import Nominatim

# Initialize Nominatim geocoder
geolocator = Nominatim(user_agent="my_geocoder")

# Geocode an address
location = geolocator.geocode("Mumbai, India")

print("Latitude:", location.latitude)
print("Longitude:", location.longitude)

#clcoding.com 


from geopy.geocoders import Nominatim

# Initialize Nominatim geocoder
geolocator = Nominatim(user_agent="my_geocoder")

# Reverse geocode coordinates
location = geolocator.reverse((26.4219999, 71.0840575))

print("Address:", location.address)

#clcoding.com


from geopy.distance import geodesic

# Coordinates of two locations
location1 = (18.521428, 73.8544541)  # Pune
location2 = (19.0785451, 72.878176)  # Mumbai

# Calculate distance between locations
distance = geodesic(location1, location2).kilometers

print("Distance betwen City :", distance, "km")

#clcoding.com



from geopy.geocoders import ArcGIS

# Initialize ArcGIS geocoder
geolocator = ArcGIS()

# Geocode an address using ArcGIS
location = geolocator.geocode("Pune, India")

print("Latitude:", location.latitude)
print("Longitude:", location.longitude)

#clcoding.com

Python Books for Kids

 



Think like a programmer with this fun beginner's guide to Python for ages 10 to 14

Kids can learn to code with the power of Python! Python Programming for Beginners is the perfect way to introduce aspiring coders to this simple and powerful coding language. This book teaches kids all about Python and programming fundamentals—and is packed full of fun and creative activities that make learning a blast!

In Python Programming for Beginners, kids will start off with the basics, learning all about fundamental coding concepts and how they can put these concepts together in Python to build their own games and programs. Each chapter focuses on a different coding concept—like variables, data types, and loops—and features three awesome coding activities to try. These activities get more difficult as they go, so young coders can see just how much their skills are growing. By the end of Python Programming for Beginners, they'll create their own fully functional sci-fi game and crack the code to a secret message!

Python Programming for Beginners features:
No coding experience needed!—Designed just for kids, this Python programming book is filled with step-by-step directions, simple explanations, and detailed code breakdowns.
Build a coding toolbox—Kids will build their programming skills, learn how to troubleshoot bugs with a handy bug-hunting guide, and practice their Python programming knowledge with cool activities.
Why Python programming?—Python is an awesome starting language for kids! It's a powerful programming language that can be used for lots of projects but features simple syntax so beginners can focus on learning programming logic.

Set kids up for a lifetime of programming success with Python Programming for Beginners .

Buy : Python Programming for Beginners: A Kid's Guide to Coding Fundamentals





Build and play your own computer games, from creative quizzes to perplexing puzzles, by coding them in the Python programming language!

Whether you're a seasoned programmer or a beginner hoping to learn Python, you'll find Coding Games in Python fun to read and easy to follow. Each chapter shows you how to construct a complete working game in simple numbered steps. Using freely available resources such as Pygame, Pygame Zero, and a downloadable pack of images and sounds, you can add animations, music, scrolling backgrounds, scenery, and other exciting professional touches.

After building the game, find out how to adapt it to create your own personalised version with secret hacks and cheat codes!

You'll master the key concepts that programmers need to write code - not just in Python, but in all programming languages. Find out what bugs, loops, flags, strings, and turtles are. Learn how to plan and design the ultimate game, and then play it to destruction as you test and debug it.

Before you know it, you'll be a coding genius!

Buy : Coding Games in Python (DK Help Your Kids)



Games and activities that teach kids ages 10+ to code with Python

Learning to code isn't as hard as it sounds—you just have to get started! Coding for Kids: Python starts kids off right with 50 fun, interactive activities that teach them the basics of the Python programming language. From learning the essential building blocks of programming to creating their very own games, kids will progress through unique lessons packed with helpful examples—and a little silliness!

Kids will follow along by starting to code (and debug their code) step by step, seeing the results of their coding in real time. Activities at the end of each chapter help test their new knowledge by combining multiple concepts. For young programmers who really want to show off their creativity, there are extra tricky challenges to tackle after each chapter. All kids need to get started is a computer and this book.

This beginner's guide to Python for kids includes:
50 Innovative exercises—Coding concepts come to life with game-based exercises for creating code blocks, drawing pictures using a prewritten module, and more.
Easy-to-follow guidance—New coders will be supported by thorough instructions, sample code, and explanations of new programming terms.
Engaging visual lessons—Colorful illustrations and screenshots for reference help capture kids' interest and keep lessons clear and simple.

Encourage kids to think independently and have fun learning an amazing new skill with this coding book for kids.


Buy : Coding for Kids: Python: Learn to Code with 50 Awesome Games and Activities




The second edition of the best-selling Python for Kids—which brings you (and your parents) into the world of programming—has been completely updated to use the latest version of Python, along with tons of new projects!

Python is a powerful programming language that’s easy to learn and fun to use! But books about programming in Python can be dull and that’s no fun for anyone.

Python for Kids brings kids (and their parents) into the wonderful world of programming. Jason R. Briggs guides you through the basics, experimenting with unique (and hilarious) example programs featuring ravenous monsters, secret agents, thieving ravens, and more. New terms are defined; code is colored and explained; puzzles stretch the brain and strengthen understanding; and full-color illustrations keep you engaged throughout.

By the end of the book, you’ll have programmed two games: a clone of the famous Pong, and “Mr. Stick Man Races for the Exit”—a platform game with jumps and animation.

This second edition is revised and updated to reflect Python 3 programming practices. There are new puzzles to inspire you and two new appendices to guide you through Python’s built-in modules and troubleshooting your code.

As you strike out on your programming adventure, you’ll learn how to:

Use fundamental data structures like lists, tuples, and dictionaries
Organize and reuse your code with functions and modules
Use control structures like loops and conditional statements
Draw shapes and patterns with Python’s turtle module
Create games, animations, and other graphical wonders with tkinter

Why should serious adults have all the fun? Python for Kids is your ticket into the amazing world of computer programming.

Covers Python 3.x which runs on Windows, macOS, Linux, even Raspberry Pi

Buy : Python for Kids, 2nd Edition: A Playful Introduction to Programming


Friday 22 March 2024

Creating QR Code with Logo

 

import qrcode

from PIL import Image


# Generate QR code for a URL

url = "https://www.clcoding.com"

qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=8, border=5)

qr.add_data(url)

qr.make(fit=True)


# Create an image with logo

image = qr.make_image(fill_color="black", back_color="pink")


# Add logo to the QR code

logo = Image.open("clcodinglogo.png")

logo_size = img.size[0] // 4

# Use Image.LANCZOS for resizing with anti-aliasing

logo = logo.resize((logo_size, logo_size), Image.LANCZOS)  

image.paste(logo, ((img.size[0] - logo.size[0]) // 2, (img.size[1] - logo.size[1]) // 2))


# Save the image

image.save("qr_code.png")

Image.open("qr_code.png")


Explantion of the code: 


This code generates a QR code for a given URL (https://www.clcoding.com) using the qrcode library and then adds a logo to the QR code using the PIL (Python Imaging Library) module. Let's break down the code step by step:

Importing libraries:

qrcode: This library is used to generate QR codes.
Image from PIL: This module provides functions to work with images.
Generating the QR code:

The URL "https://www.clcoding.com" is assigned to the variable url.
A QRCode object is created with specific parameters:
version: The version of the QR code (higher versions can store more data).
error_correction: The error correction level of the QR code.
box_size: The size of each box in the QR code.
border: The width of the border around the QR code.
The URL data is added to the QR code using the add_data() method.
The make() method is called to generate the QR code, and fit=True ensures that the size of the QR code fits the data.
Creating an image with the QR code:

The make_image() method is called to create an image representation of the QR code, with specified fill and background colors (fill_color="black", back_color="pink").
The resulting image is stored in the variable image.
Adding a logo to the QR code:

An image of the logo (clcodinglogo.png) is opened using the Image.open() method and stored in the variable logo.
The size of the logo is calculated to be a quarter of the size of the QR code.
The logo is resized using the resize() method with anti-aliasing (Image.LANCZOS filter) to prevent distortion.
The logo is pasted onto the QR code image at the center using the paste() method.
Saving and displaying the final image:

The QR code image with the logo is saved as "qr_code.png" using the save() method.
The saved image is opened and displayed using Image.open().
This code demonstrates how to generate a customized QR code with a logo using Python. Make sure to replace "clcodinglogo.png" with the filename of your logo image.

Tuesday 19 March 2024

The statistics module in Python

 

Calculating Mean:

import statistics


data = [1, 2, 3, 4, 5]

mean = statistics.mean(data)

print("Mean:", mean)


#clcoding.com

Mean: 3

Calculating Median:

import statistics


data = [1, 2, 3, 4, 5]

median = statistics.median(data)

print("Median:", median)


#clcoding.com

Median: 3

Calculating Mode:

import statistics


data = [1, 2, 2, 3, 4, 4, 4, 5]

mode = statistics.mode(data)

print("Mode:", mode)


#clcoding.com

Mode: 4

Calculating Variance:

import statistics


data = [1, 2, 3, 4, 5]

variance = statistics.variance(data)

print("Variance:", variance)


#clcoding.com

Variance: 2.5

Calculating Standard Deviation:

import statistics


data = [1, 2, 3, 4, 5]

std_dev = statistics.stdev(data)

print("Standard Deviation:", std_dev)


#clcoding.com

Standard Deviation: 1.5811388300841898

Calculating Quartiles:

import statistics


data = [1, 2, 3, 4, 5]

q1 = statistics.quantiles(data, n=4)[0]

q3 = statistics.quantiles(data, n=4)[-1]

print("First Quartile (Q1):", q1)

print("Third Quartile (Q3):", q3)


#clcoding.com

First Quartile (Q1): 1.5

Third Quartile (Q3): 4.5

Calculating Correlation Coefficient:

import statistics


data1 = [1, 2, 3, 4, 5]

data2 = [2, 4, 6, 8, 10]

corr_coeff = statistics.correlation(data1, data2)

print("Correlation Coefficient:", corr_coeff)


#clcoding.com

Correlation Coefficient: 1.0


Monday 18 March 2024

The faker library in Python

 


The faker library in Python


Installing faker:

pip install faker

Generating Fake Names:

from faker import Faker

# Create a Faker object
faker = Faker()

# Generate a fake name
fake_name = faker.name()
print("Fake Name:", fake_name)

#clcoding.com
Fake Name: Anthony Ortiz

Generating Fake Addresses:

from faker import Faker

# Create a Faker object
faker = Faker()

# Generate a fake address
fake_address = faker.address()
print("Fake Address:", fake_address)

#clcoding.com 
Fake Address: 098 Parker Burg Suite 277
Olsonborough, IN 35433

Generating Fake Email Addresses:

from faker import Faker

# Create a Faker object
faker = Faker()

# Generate a fake email address
fake_email = faker.email()
print("Fake Email Address:", fake_email)

#clcoding.com 
Fake Email Address: choward@example.com

Generating Fake Text:

from faker import Faker

# Create a Faker object
faker = Faker()

# Generate fake text
fake_text = faker.text()
print("Fake Text:\n", fake_text)

#clcoding.com
Fake Text:
 Election huge event. Remember go else purpose specific detail position eight. High project outside quickly try research.
Degree affect detail together. Way company along relate set.

Generating Fake Dates:

from faker import Faker

# Create a Faker object
faker = Faker()

# Generate a fake date
fake_date = faker.date_of_birth()
print("Fake Date of Birth:", fake_date)

#clcoding.com
Fake Date of Birth: 1950-10-06

Generating Fake User Profiles:

from faker import Faker

# Create a Faker object
faker = Faker()

# Generate a fake user profile
fake_profile = faker.profile()
print("Fake User Profile:", fake_profile)

#clcoding.com
Fake User Profile: {'job': 'Insurance claims handler', 'company': 'Mitchell-Martinez', 'ssn': '590-06-5154', 'residence': '90056 Medina Brooks\nMeyermouth, AK 19255', 'current_location': (Decimal('25.254868'), Decimal('19.597316')), 'blood_group': 'B+', 'website': ['https://johnson-bentley.com/', 'https://stevenson.com/'], 'username': 'qparker', 'name': 'Jay Sims', 'sex': 'M', 'address': '6742 Moore Fields\nMartinton, ME 47664', 'mail': 'fmiranda@hotmail.com', 'birthdate': datetime.date(1985, 8, 7)}

Friday 15 March 2024

The json library in Python

 


The json library in Python

1. Encoding Python Data to JSON:

import json

# Python dictionary to be encoded to JSON

data = {

    "name": "John",

    "age": 30,

    "city": "New York"

}

# Encode the Python dictionary to JSON

json_data = json.dumps(data)

print("Encoded JSON:", json_data)


#clcoding.com

Encoded JSON: {"name": "John", "age": 30, "city": "New York"}

2. Decoding JSON to Python Data:

import json

# JSON data to be decoded to Python

json_data = '{"name": "John", "age": 30, "city": "New York"}'

# Decode the JSON data to a Python dictionary

data = json.loads(json_data)

print("Decoded Python Data:", data)

#clcoding.com

Decoded Python Data: {'name': 'John', 'age': 30, 'city': 'New York'}

3. Reading JSON from a File:

clcoding

import json

# Read JSON data from a file

with open('clcoding.json', 'r') as file:

    data = json.load(file)

print("JSON Data from File:", data)

#clcoding.com

JSON Data from File: {'We are supporting freely to everyone. Join us for live support. \n\nWhatApp Support: wa.me/919767292502\n\nInstagram Support : https://www.instagram.com/pythonclcoding/\n\nFree program: https://www.clcoding.com/\n\nFree Codes: https://clcoding.quora.com/\n\nFree Support: pythonclcoding@gmail.com\n\nLive Support: https://t.me/pythonclcoding\n\nLike us: https://www.facebook.com/pythonclcoding\n\nJoin us: https://www.facebook.com/groups/pythonclcoding': None}

4. Writing JSON to a File:

import json

# Python dictionary to be written to a JSON file

data = {

    "name": "John",

    "age": 30,

    "city": "New York"

}

# Write the Python dictionary to a JSON file

with open('output.json', 'w') as file:

    json.dump(data, file)

    #clcoding.com

5. Handling JSON Errors:

import json

# JSON data with syntax error

json_data = '{"name": "John", "age": 30, "city": "New York"'

try:

    # Attempt to decode JSON data

    data = json.loads(json_data)

except json.JSONDecodeError as e:

    # Handle JSON decoding error

    print("Error decoding JSON:", e)

    #clcoding.com

Error decoding JSON: Expecting ',' delimiter: line 1 column 47 (char 46)

Thursday 14 March 2024

Learn hashlib library in Python

 


1. Hashing Strings:

import hashlib

# Hash a string using SHA256 algorithm

string_to_hash = "Hello, World!"

hashed_string = hashlib.sha256(string_to_hash.encode()).hexdigest()

print("Original String:", string_to_hash)

print("Hashed String:", hashed_string)

#clcoding.com 

Original String: Hello, World!

Hashed String: dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f

2. Hashing Files:

#clcoding.com 

import hashlib

def calculate_file_hash(file_path, algorithm='sha256'):

    # Choose the hash algorithm

    hash_algorithm = getattr(hashlib, algorithm)()

    # Read the file in binary mode and update the hash object

    with open(file_path, 'rb') as file:

        for chunk in iter(lambda: file.read(4096), b''):

            hash_algorithm.update(chunk)

    # Get the hexadecimal representation of the hash value

    hash_value = hash_algorithm.hexdigest()

    return hash_value

# Example usage

file_path = 'example.txt'

file_hash = calculate_file_hash(file_path)

print("SHA-256 Hash of the file:", file_hash)

#clcoding.com 

SHA-256 Hash of the file: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

3. Using Different Hash Algorithms:

import hashlib

# Hash a string using different algorithms

string_to_hash = "Hello, World!"

# MD5

md5_hash = hashlib.md5(string_to_hash.encode()).hexdigest()

# SHA1

sha1_hash = hashlib.sha1(string_to_hash.encode()).hexdigest()

# SHA512

sha512_hash = hashlib.sha512(string_to_hash.encode()).hexdigest()

print("MD5 Hash:", md5_hash)

print("SHA1 Hash:", sha1_hash)

print("SHA512 Hash:", sha512_hash)

#clcoding.com 

MD5 Hash: 65a8e27d8879283831b664bd8b7f0ad4

SHA1 Hash: 0a0a9f2a6772942557ab5355d76af442f8f65e01

SHA512 Hash: 374d794a95cdcfd8b35993185fef9ba368f160d8daf432d08ba9f1ed1e5abe6cc69291e0fa2fe0006a52570ef18c19def4e617c33ce52ef0a6e5fbe318cb0387

4. Hashing Passwords (Securely):

import hashlib

# Hash a password securely using a salt

password = "my_password"

salt = "random_salt"


hashed_password = hashlib.pbkdf2_hmac('sha256', password.encode(), salt.encode(), 100000)

hashed_password_hex = hashed_password.hex()

print("Salted and Hashed Password:", hashed_password_hex)


#clcoding.com 

Salted and Hashed Password: b18597b62cda4415c995eaff30f61460da8ff4d758d3880f80593ed5866dcf98

5. Verifying Passwords:

import hashlib

# Verify a password against a stored hash

stored_hash = "stored_hashed_password"

def verify_password(password, stored_hash):

    input_hash = hashlib.sha256(password.encode()).hexdigest()

    if input_hash == stored_hash:

        return True

    else:

        return False

password_to_verify = "password_to_verify"

if verify_password(password_to_verify, stored_hash):

    print("Password is correct!")

else:

    print("Password is incorrect.")

    

#clcoding.com 

Password is incorrect.

6. Hashing a String using SHA-256:

import hashlib

# Create a hash object

hash_object = hashlib.sha256()

# Update the hash object with the input data

input_data = b'Hello, World!'

hash_object.update(input_data)

# Get the hexadecimal representation of the hash value

hash_value = hash_object.hexdigest()

print("SHA-256 Hash:", hash_value)

#clcoding.com 

SHA-256 Hash: dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f

7. Hashing a String using MD5:

import hashlib

# Create a hash object

hash_object = hashlib.md5()

# Update the hash object with the input data

input_data = b'Hello, World!'

hash_object.update(input_data)

# Get the hexadecimal representation of the hash value

hash_value = hash_object.hexdigest()

print("MD5 Hash:", hash_value)

#clcoding.com 

MD5 Hash: 65a8e27d8879283831b664bd8b7f0ad4


Wednesday 13 March 2024

Learn psutil library in Python 🧵:

 


Learn psutil library in Python

pip install psutil

1. Getting CPU Information:

import psutil

# Get CPU information

cpu_count = psutil.cpu_count()

cpu_percent = psutil.cpu_percent(interval=1)


print("CPU Count:", cpu_count)

print("CPU Percent:", cpu_percent)


#clcoding.com 

CPU Count: 8

CPU Percent: 6.9

2. Getting Memory Information:

import psutil

# Get memory information

memory = psutil.virtual_memory()

total_memory = memory.total

available_memory = memory.available

used_memory = memory.used

percent_memory = memory.percent

print("Total Memory:", total_memory)

print("Available Memory:", available_memory)

print("Used Memory:", used_memory)

print("Memory Percent:", percent_memory)

#clcoding.com

Total Memory: 8446738432

Available Memory: 721600512

Used Memory: 7725137920

Memory Percent: 91.5

3. Listing Running Processes:

import psutil

# List running processes

for process in psutil.process_iter():

    print(process.pid, process.name())

    #clcoding.com

0 System Idle Process

4 System

124 Registry

252 chrome.exe

408 PowerToys.Peek.UI.exe

436 msedge.exe

452 svchost.exe

504 smss.exe

520 svchost.exe

532 RuntimeBroker.exe

544 TextInputHost.exe

548 svchost.exe

680 csrss.exe

704 fontdrvhost.exe

768 wininit.exe

776 chrome.exe

804 chrome.exe

848 services.exe

924 lsass.exe

1036 WUDFHost.exe

1100 svchost.exe

1148 svchost.exe

1160 SgrmBroker.exe

1260 dllhost.exe

1284 PowerToys.exe

1328 svchost.exe

1392 svchost.exe

1400 svchost.exe

1408 svchost.exe

1488 svchost.exe

1504 svchost.exe

1512 svchost.exe

1600 SmartAudio3.exe

1608 svchost.exe

1668 svchost.exe

1716 svchost.exe

1724 IntelCpHDCPSvc.exe

1732 svchost.exe

1752 svchost.exe

1796 TiWorker.exe

1828 svchost.exe

1920 chrome.exe

1972 svchost.exe

1992 svchost.exe

2016 svchost.exe

2052 svchost.exe

2060 svchost.exe

2068 IntelCpHeciSvc.exe

2148 igfxCUIService.exe

2168 svchost.exe

2224 svchost.exe

2260 svchost.exe

2316 svchost.exe

2360 chrome.exe

2364 svchost.exe

2400 MsMpEng.exe

2420 svchost.exe

2428 svchost.exe

2448 PowerToys.FancyZones.exe

2480 screenrec.exe

2488 svchost.exe

2496 svchost.exe

2504 svchost.exe

2552 svchost.exe

2604 svchost.exe

2616 MemCompression

2716 svchost.exe

2792 chrome.exe

2796 dasHost.exe

2804 chrome.exe

2852 svchost.exe

2876 svchost.exe

2932 CxAudioSvc.exe

3016 svchost.exe

3240 svchost.exe

3416 svchost.exe

3480 svchost.exe

3536 spoolsv.exe

3620 svchost.exe

3660 svchost.exe

3700 svchost.exe

3752 RuntimeBroker.exe

3848 taskhostw.exe

3976 svchost.exe

3984 svchost.exe

3992 svchost.exe

4000 svchost.exe

4008 svchost.exe

4016 svchost.exe

4024 svchost.exe

4032 svchost.exe

4100 svchost.exe

4132 OneApp.IGCC.WinService.exe

4140 AnyDesk.exe

4148 armsvc.exe

4156 CxUtilSvc.exe

4208 WMIRegistrationService.exe

4284 msedge.exe

4312 svchost.exe

4320 AGMService.exe

4340 svchost.exe

4488 chrome.exe

4516 svchost.exe

4584 svchost.exe

4720 jhi_service.exe

4928 chrome.exe

5004 chrome.exe

5176 dwm.exe

5348 svchost.exe

5368 Flow.exe

5380 svchost.exe

5536 chrome.exe

5540 chrome.exe

5584 audiodg.exe

5620 svchost.exe

5724 svchost.exe

5776 svchost.exe

5992 ctfmon.exe

6032 CompPkgSrv.exe

6056 SearchProtocolHost.exe

6076 msedge.exe

6120 SearchIndexer.exe

6128 RuntimeBroker.exe

6156 svchost.exe

6192 MoUsoCoreWorker.exe

6380 PowerToys.PowerLauncher.exe

6424 PowerToys.Awake.exe

6480 msedge.exe

6596 svchost.exe

6740 svchost.exe

6792 winlogon.exe

6856 TrustedInstaller.exe

6872 svchost.exe

6888 igfxEM.exe

6908 svchost.exe

6948 chrome.exe

7140 csrss.exe

7296 PowerToys.KeyboardManagerEngine.exe

7336 WhatsApp.exe

7348 chrome.exe

7416 chrome.exe

7440 MusNotifyIcon.exe

7444 StartMenuExperienceHost.exe

7480 svchost.exe

7520 chrome.exe

7556 SearchApp.exe

7560 SecurityHealthService.exe

7720 msedge.exe

8220 MmReminderService.exe

8316 RuntimeBroker.exe

8636 svchost.exe

8836 python.exe

9088 ShellExperienceHost.exe

9284 svchost.exe

9344 NisSrv.exe

9560 msedge.exe

9664 chrome.exe

9736 chrome.exe

9784 SearchApp.exe

9808 svchost.exe

9868 python.exe

9884 svchost.exe

9908 chrome.exe

9936 chrome.exe

9996 QtWebEngineProcess.exe

10012 taskhostw.exe

10024 chrome.exe

10148 svchost.exe

10228 svchost.exe

10236 PowerToys.CropAndLock.exe

10304 Taskmgr.exe

10324 Video.UI.exe

10584 svchost.exe

10680 chrome.exe

10920 LockApp.exe

11064 chrome.exe

11176 chrome.exe

11188 msedge.exe

11396 msedge.exe

11500 QtWebEngineProcess.exe

11592 svchost.exe

12132 msedge.exe

12212 RuntimeBroker.exe

12360 RuntimeBroker.exe

12500 chrome.exe

12596 python.exe

12704 chrome.exe

12744 svchost.exe

12832 svchost.exe

12848 MicTray64.exe

12852 fontdrvhost.exe

12992 chrome.exe

13092 chrome.exe

13268 chrome.exe

13332 chrome.exe

13388 sihost.exe

13572 chrome.exe

13760 SecurityHealthSystray.exe

13792 msedge.exe

13880 fodhelper.exe

13900 chrome.exe

14160 UserOOBEBroker.exe

14220 RuntimeBroker.exe

14260 chrome.exe

14356 msedge.exe

14572 chrome.exe

14648 chrome.exe

14696 PowerToys.AlwaysOnTop.exe

14852 chrome.exe

14868 PowerToys.ColorPickerUI.exe

14876 conhost.exe

14888 PowerToys.PowerOCR.exe

14948 chrome.exe

15324 explorer.exe

4. Getting Process Information:

252

import psutil

# Get information for a specific process

pid = 252  # Replace with the process ID of interest

process = psutil.Process(pid)

print("Process Name:", process.name())

print("Process Status:", process.status())

print("Process CPU Percent:", process.cpu_percent(interval=1))

print("Process Memory Info:", process.memory_info())

#clcoding.com

Process Name: chrome.exe

Process Status: running

Process CPU Percent: 0.0

Process Memory Info: pmem(rss=29597696, vms=24637440, num_page_faults=14245, peak_wset=37335040, wset=29597696, peak_paged_pool=635560, paged_pool=635560, peak_nonpaged_pool=21344, nonpaged_pool=17536, pagefile=24637440, peak_pagefile=33103872, private=24637440)

5. Killing a Process:

import psutil

# Kill a process

pid_to_kill = 10088  

# Replace with the process ID to kill

process_to_kill = psutil.Process(pid_to_kill)

process_to_kill.terminate()

#clcoding.com

6. Getting Disk Usage:

import psutil

# Get disk usage information

disk_usage = psutil.disk_usage('/')

total_disk_space = disk_usage.total

used_disk_space = disk_usage.used

free_disk_space = disk_usage.free

disk_usage_percent = disk_usage.percent

print("Total Disk Space:", total_disk_space)

print("Used Disk Space:", used_disk_space)

print("Free Disk Space:", free_disk_space)

print("Disk Usage Percent:", disk_usage_percent)

#clcoding.com

Total Disk Space: 479491600384

Used Disk Space: 414899838976

Free Disk Space: 64591761408

Disk Usage Percent: 86.5

Popular Posts

Categories

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

Followers

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