0% found this document useful (0 votes)
3 views33 pages

Unit V Python

The document provides an overview of Python file handling, including advantages and disadvantages, as well as methods for opening, reading, writing, and deleting files. It also covers directory management using the os module, such as getting the current working directory and listing directory contents. Additionally, it introduces the calendar module for displaying calendars and the time module for working with time representations in Python.

Uploaded by

priyangas100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views33 pages

Unit V Python

The document provides an overview of Python file handling, including advantages and disadvantages, as well as methods for opening, reading, writing, and deleting files. It also covers directory management using the os module, such as getting the current working directory and listing directory contents. Additionally, it introduces the calendar module for displaying calendars and the time module for working with time representations in Python.

Uploaded by

priyangas100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

4.

1 Python File Handling


Python supports file handling and allows users to handle files i.e., to read and write files,
along with many other file handling options, to operate on files. The concept of file handling
has stretched over various other languages, but the implementation is either complicated or
lengthy, like other concepts of Python, this concept here is also easy and short.
Advantages of File Handling in Python
1. Versatility : File handling in Python allows you to perform a wide range of operations,
such as creating, reading, writing, appending, renaming, and deleting files.
2. Flexibility : File handling in Python is highly flexible, as it allows you to work with
different file types (e.g. text files, binary files, CSV files , etc.), and to perform different
operations on files (e.g. read, write, append, etc.).
3. User – friendly : Python provides a user-friendly interface for file handling, making it
easy to create, read, and manipulate files.
4. Cross-platform : Python file-handling functions work across different platforms (e.g.
Windows, Mac, Linux), allowing for seamless integration and compatibility.
5. Disadvantages of File Handling in Python
6. Error-prone: File handling operations in Python can be prone to errors, especially if
the code is not carefully written or if there are issues with the file system (e.g. file
permissions, file locks, etc.).
7. Security risks : File handling in Python can also pose security risks, especially if the
program accepts user input that can be used to access or modify sensitive files on the
system.
8. Complexity : File handling in Python can be complex, especially when working with
more advanced file formats or operations. Careful attention must be paid to the code to
ensure that files are handled properly and securely.
9. Performance : File handling operations in Python can be slower than other
programming languages, especially when dealing with large files or performing
complex operations.
10. For this article, we will consider the following ” [Link] ” file as an example.
Python File Open
Before performing any operation on the file like reading or writing, first, we have to
open that file. For this, we should use Python’s inbuilt function open() but at the time of
opening, we have to specify the mode, which represents the purpose of the opening file.
f = open(filename, mode)
Where the following mode is supported:
 r: open an existing file for a read operation.
 w: open an existing file for a write operation. If the file already contains some data, then
it will be overridden but if the file is not present then it creates the file as well.
 a: open an existing file for append operation. It won’t override existing data
Working in Read mode
There is more than one way to How to read from a file in Python . Let us see how we
can read the content of a file in read mode.
# Python code to illustrate read() mode
file = open("[Link]", "r")
print ([Link]())
Output:
Hello world
GeeksforGeeks
123 456
Creating a File using the write() Function
Just like reading a file in Python, there are a number of ways to Writing to file in
Python . Let us see how we can write the content of a file using the write() function in
Python.
Working in Write Mode
Let’s see how to create a file and how the write mode works.
Example 1: In this example, we will see how the write mode and the write() function is used to
write in a file. The close() command terminates all the resources in use and frees the system of
this particular program.
# Python code to create a file
file = open('[Link]','w')
[Link]("This is the write command")
[Link]("It allows us to write in a particular file")
[Link]()
Output:
This is the write commandIt allows us to write in a particular file
Read Lines
You can return one line by using the readline() method:
Example
Read one line of the file:
f = open("[Link]", "r")
print([Link]())
By calling readline() two times, you can read the two first lines:
Example
Read two lines of the file:
f = open("[Link]", "r")
print([Link]())
print([Link]())
By looping through the lines of the file, you can read the whole file, line by line:
Example
Loop through the file line by line:
f = open("[Link]", "r")
for x in f:
print(x

Close Files
It is a good practice to always close the file when you are done with it.
Example
Close the file when you are finished with it:
f = open("[Link]", "r")
print([Link]())
[Link]()
Create a New File
To create a new file in Python, use the open() method, with one of the following
parameters:
"x" - Create - will create a file, returns an error if the file exists
"a" - Append - will create a file if the specified file does not exists
"w" - Write - will create a file if the specified file does not exists
Example
Create a file called "[Link]":
f = open("[Link]", "x")
Result: a new empty file is created!
Example
Create a new file if it does not exist:
f = open("[Link]", "w")
Delete a File
To delete a file, you must import the OS module, and run its [Link]() function:
Remove the file "[Link]":
import os
[Link]("[Link]")

Check if File exist:


To avoid getting an error, you might want to check if the file exists before you try to delete it:
Example
Check if file exists, then delete it:
import os
if [Link]("[Link]"):
[Link]("[Link]")
else:
print("The file does not exist")

Delete Folder
To delete an entire folder, use the [Link]() method:
Example
Remove the folder "myfolder":
import os
[Link]("myfolder")

4.2 Directory
Get Current Working Directory
To retrieve the current working directory in Python, you can use
the [Link]() function. This function returns a string representing the current working
directory where the Python script is executing.
Syntax
Following is the basic syntax of the getcwd() function in Python −
[Link]()
Example
Following is an example to display the current working directory using the getcwd() function −
Open Compiler
import os
current_directory = [Link]()
print(f"Current working directory: {current_directory}")
We get the output as follows −
Current working directory: /home/cg/root/667ba7570a5b7

Listing Files and Directories


You can list the contents of a directory using the [Link]() function. This function
returns a list of all files and directories within the specified directory path.
Example
In the example below, we are listing the contents of the specified directory path using
the listdir() function −
import os
directory_path = r"D:\MyFolder\Pictures"
try:
contents = [Link](directory_path)
print(f"Contents of '{directory_path}':")
for item in contents:
print(item)
except OSError as e:
print(f"Error: Failed to list contents of directory '{directory_path}'. {e}")

Output of the above code is as shown below −


Contents of 'D:\MyFolder\Pictures':
Camera Roll
[Link]
Saved Pictures
Screenshots

Changing the Current Working Directory


You can change the current directory using the chdir() method. This method takes an
argument, which is the name of the directory that you want to make the current directory.
Syntax
Following is the syntax of the chdir() method in Python −
[Link]("newdir")
Example
Following is an example to change the current directory to Desktop using the chdir() method −
import os
new_directory = r"D:\MyFolder\Pictures"

try:
[Link](new_directory)
print(f"Current working directory changed to '{new_directory}'.")
except OSError as e:
print(f"Error: Failed to change working directory to '{new_directory}'. {e}")
We get the output as shown below −
Current working directory changed to 'D:\MyFolder\Pictures'.

Removing a Directory
You can remove an empty directory in Python using the [Link]() method. If the
directory contains files or other directories, you can use [Link]() method to delete
it recursively.
Syntax
Following is the basic syntax to delete a directory in Python −
[Link](directory_path)
# or
[Link](directory_path)
Example
In the following example, we remove an empty directory using the [Link]() method −
import os
directory_path = r"D:\MyFolder\new_dir"

try:
[Link](directory_path)
print(f"Directory '{directory_path}' successfully removed.")
except OSError as e:
print(f"Error: Failed to remove directory '{directory_path}'. {e}")
It will produce the following output −
Directory 'D:\MyFolder\new_dir' successfully removed.

5.3 Python | Calendar Module


Python defines an inbuilt module calendar that handles operations related to the
calendar. In this article, we will see the Python Program to Display Calendar.
Calendar Module in Python
The calendar module allows us to output calendars like the program and provides
additional useful functions related to the calendar. Functions and classes defined in the
calendar module use an idealized calendar, the current Gregorian calendar is extended
indefinitely in both directions. By default, these calendars have Monday as the first day of the
week, and Sunday as the last (the European convention).
Display the Python Calendar of a given Month
The code uses Python’s calendar module to print a calendar for the specified year (yy)
and month (mm). In this case, it prints the calendar for November 2017. Python Program to
Display Calendar
import calendar
yy = 2017
mm = 11
print([Link](yy, mm))

Output:
Display the Python calendar of the given Year
The code you provided uses Python’s calendar module to print a calendar for the year
2018.

import calendar
print ("The calendar of year 2018 is : ")
print ([Link](2018))

class [Link]
The calendar class creates a calendar object. A calendar object provides several
methods that can be used for preparing the calendar data for formatting. This class doesn’t do
any formatting itself. This is the job of subclasses. The calendar class allows the calculations
for various tasks based on date, month, and year and provides the following methods:
Function Description
iterweekdays() Returns an iterator for the weekday numbers that will be used for one week
itermonthdates() Returns an iterator for the month (1–12) in the year
itermonthdays() Returns an iterator of a specified month and a year
class [Link]
TextCalendar class can be used to generate plain text calendars. TextCalendar class in
Python allows you to edit the calendar and use it as per your requirement.
Function Description
formatmonth() This method is used to get the month’s
calendar in a multi-line string
prmonth() This method is used to print a month’s
calendar as returned by formatmonth()
formatyear() This method is used to get m-column
calendar for an entire year as a multi-line
string

class [Link] :
HTMLCalendar class can be used to generate HTML calendars. HTMLCalendar class
in Python allows you to edit the calendar and use as per your requirement.
Function Description
formatmonth() This method is used to get the month’s
calendar as an HTML table
formatyear() This method is used to get a year’s
calendar as an HTML table.
formatyearpage() This method is used to get the year’s
calendar as a complete HTML page

Simple TextCalendar class


For simple text calendars calendar module provides the following functions:
Function Description
setfirstweekday() This method sets the day start number of
the week
firstweekday() This method returns the first weekday
number. By default 0 (Monday)
isleap() This method checks if the year mentioned
in the argument is leap or not
leapdays() This method returns the number of leap
days between the specified years in
arguments
Getting the Current Time
To translate a time instant from seconds since the epoch floating-point value into a
time-tuple, pass the floating-point value to a function (e.g., localtime) that returns a time-tuple
with all valid nine items.
import time
localtime = [Link]([Link]())
print ("Local current time :", localtime)
This would produce the following result, which could be formatted in any other presentable
form −
Local current time : time.struct_time(tm_year=2023, tm_mon=4, tm_mday=19, tm_hour=23,
tm_min=42, tm_sec=41, tm_wday=2, tm_yday=109, tm_isdst=0)

Getting the Formatted Time


You can format any time as per your requirement, but a simple method to get time in a
readable format is asctime() −
Open Compiler
import time
localtime = [Link]( [Link]([Link]()) )
print ("Local current time :", localtime)
This would produce the following output −
Local current time : Wed Apr 19 [Link] 2023

The time Module


There is a popular time module available in Python, which provides functions for
working with times and for converting between representations. Here is the list of all available
methods.
[Link]. Function with Description
1 [Link]
The offset of the local DST timezone, in seconds west of UTC, if one is
defined. This is negative if the local DST timezone is east of UTC (as in
Western Europe, including the UK). Only use this if daylight is
nonzero.
2 [Link]([tupletime])
Accepts a time-tuple and returns a readable 24-character string such as
'Tue Dec 11 [Link] 2008'.
3 [Link]( )
Returns the current CPU time as a floating-point number of seconds. To
measure computational costs of different approaches, the value of
[Link] is more useful than that of [Link]().

Python time Module


An object time class represents the local time of the day. It is independent of any
particular day. It the object contains the tzinfo details, it is the aware object. If it is None
then the time object is the naive object.
Syntax
[Link](hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
All arguments are optional. tzinfo may be None, or an instance of a tzinfo subclass. The
remaining arguments must be integers in the following ranges −
hour − 0 <= hour < 24,
minute − 0 <= minute < 60,
second − 0 <= second < 60,
microsecond − 0 <= microsecond < 1000000
If any of the arguments are outside those ranges is given, ValueError is raised.
Example
Open Compiler
from datetime import time
time1 = time(8, 14, 36)
print("Time:", time1)

time2 = time(minute = 12)


print("time", time2)

time3 = time()
print("time", time3)

time4 = time(hour = 26)


It will produce the following output −
Time: [Link]
time [Link]
time [Link]
Traceback (most recent call last):
File "/home/cg/root/64b912f27faef/[Link]", line 12, in
time4 = time(hour = 26)
ValueError: hour must be in 0..23

Class attributes
1. [Link] − The earliest representable time, time(0, 0, 0, 0).
2. [Link] − The latest representable time, time(23, 59, 59, 999999).
3. [Link] − The smallest possible difference between non-equal time objects.
Example
Open Compiler
from datetime import time
print([Link])
print([Link])
print ([Link])
It will produce the following output −
[Link]
[Link].999999
[Link].000001
Instance attributes
1. [Link] − In range(24)
2. [Link] − In range(60)
3. [Link] − In range(60)
4. [Link] − In range(1000000)
5. [Link] − the tzinfo argument to the time constructor, or None.
Example
from datetime import time
t = time(8,23,45,5000)
print([Link])
print([Link])
print ([Link])
print ([Link])
It will produce the following output −
8
23
455000

Instance Methods of time Object


1. replace() − Return a time with the same value, except for those attributes given
new values by whichever keyword arguments are specified.
2. isoformat() − Return a string representing the time in ISO 8601 format
3. __str__() − For a time t, str(t) is equivalent to [Link]().
4. strftime(format) − Return a string representing the time, controlled by an explicit
format string.
5. __format__(format) − Same as [Link]().
6. utcoffset() − If tzinfo is None, returns None, else returns
[Link](None),
7. dst() − If tzinfo is None, returns None, else returns [Link](None),
8. tzname() − If tzinfo is None, returns None, else returns [Link](None),
or raises an exception

Concurrency in Python
Concurrency is one approach to drastically increase the performance of your Python
programs. Concurrency allows several processes to be completed concurrently, maximizing the
utilization of your system’s resources. Concurrency can be achieved in Python by the use of
numerous methods and modules, such as threading, multiprocessing, and asynchronous
programming. In this article, we will learn about What is concurrency in Python, the processes
required to implement it, some good examples, and the output results.
What is Concurrent Programming?
It refers to the ability of the computer to manage multiple tasks at the same time. These
tasks might not be compulsory to execute at the exact same moment but they might interleaved
or executed in overlapping periods of time. The main goal of concurrency is to handle multiple
user inputs, manage several I/O tasks, or process multiple independent tasks.
What is Parallelism?
Parallelism is a subset of concurrency where tasks or processes are executed
simultaneously, As we know concurrency is about dealing with multiple tasks, whereas
parallelism is about executing them simultaneously to speed computation. The primary goal is
to improve computational efficiency and speed up the [performance of the system.
Thread-Based Concurrency: Threading is a technique for producing lightweight threads
(sometimes known as “worker threads”) in a single step. Because these threads share the same
memory region, they are ideal for I/O-bound activities.
Process-Based Concurrency: Multiprocessing entails the execution of several
processes, each with its own memory space. Because it can use several CPU cores, this is
appropriate for CPU-bound activities.
Coroutine-Based Concurrency: Asynchronous programming, with ‘asyncio’ , ‘async’, and
‘await’ keywords, is ideal for efficiently managing I/O-bound processes. It enables tasks to
pause and hand over control to other tasks during I/O operations without causing the entire
program to crash.
Concurrency vs. Parallelism
 Concurrency: It refers to the execution of many tasks in overlapping time periods, but
not necessarily concurrently. It is appropriate for I/O-bound operations that frequently
rely on external resources such as files or network data.
 Parallelism: On the other hand, is running many processes at the same time, generally
using multiple CPU cores. It is best suited for CPU-intensive jobs requiring lengthy
processing.
 Steps to Implement Concurrency in Python
 Select the Appropriate Approach:Determine whether your software is CPU or I/O
bound. Threading is best for I/O-bound operations whereas multiprocessing is best for
CPU-bound workloads.
 Import the Appropriate Libraries: Import the threading, multiprocessing, or asyncio
libraries, depending on your method.
 Create Worker Roles: Define the functions or methods that represent the jobs you
want to run simultaneously.
 Create Threads, Processes, and Tasks: To execute your worker functions
concurrently, create and launch threads, processes, or asynchronous tasks.
 Control Synchronization (if necessary): When employing threads or processes, use
synchronization methods such as locks or semaphores to prevent data corruption in
shared resources.
 Wait for the job to be finished: Make sure your main application waits for all
concurrent jobs to finish before continuing.
Thread-Based Concurrency
Import the time and threading modules. Print_numbers and print_letters are two
functions that simulate time-consuming jobs. To imitate a time-consuming task, these
programs print numbers and letters with a 1-second delay between each print. Create
two Thread objects, thread1 and thread2, and use the target argument to assign each to
one of the functions (print_numbers and print_letters). Use the start() function to start
both threads. This starts the parallel execution of the functions. Use the join()
method for each thread to ensure that the main thread waits for threads 1 and 2 to finish
before continuing. This synchronization step is required to avoid the main program
ending prematurely. Finally, print a message indicating that both threads are complete.

import threading
import time
# Function to simulate a time-consuming task
def print_numbers():
for i in range(1, 6):
print(f"Printing number {i}")
[Link](1) # Simulate a delay of 1 second
# Function to simulate another task
def print_letters():
for letter in 'Geeks':
print(f"Printing letter {letter}")
[Link](1) # Simulate a delay of 1 second
# Create two thread objects, one for each function
thread1 = [Link](target=print_numbers)
thread2 = [Link](target=print_letters)

# Start the threads


[Link]()
[Link]()

# The main thread waits for both threads to finish


[Link]()
[Link]()

print("Both threads have finished.")

Output:
Printing number 1
Printing letter G
Printing number 2
Printing letter e
Printing letter e
Printing number 3
Printing letter k
Printing number 4
Printing letter s
Printing number 5
Both threads have finished.
When you run this code, you’ll notice that the two threads execute the two functions,
print_numbers and print_letters, concurrently. As a result, the output from both methods will
be interleaved, and each function will introduce a 1-second delay between prints, imitating a
time-consuming operation. The join() functions ensure that the main program awaits the
completion of both threads before printing the final message.
Process-Based Concurrency
Bring the multiprocessing module into the program. Define a square(x) function that
squares a given [Link] a number list with the integers [1, 2, 3, 4, 5].Using
multiprocessing, create a multiprocessing pool. To manage worker processes, use Pool().Apply
the square function to each number concurrently with [Link]() to distribute the work among
[Link] a list of the squared result and then print the values that have been squared

import multiprocessing
# Function to square a number
def square(x):
return x * x
if __name__ == "__main__":
# Define a list of numbers
numbers = [1, 2, 3, 4, 5]

# Create a multiprocessing pool


with [Link]() as pool:
# Use the map method to apply the 'square ' function to each number in parallel
results = [Link](square, numbers)
# Print the results
print(results)Output:
[1, 4, 9, 16, 25]

This code parallelizes the square function on each number, utilizing many CPU cores for
quicker execution of CPU-bound operations.
Coroutine-Based Concurrency (using asyncio)
The code is broken down as follows: For asynchronous programming, import the
asyncio [Link] await [Link](1), define an asynchronous function greet(name)
that simulates a greeting with a 1-second [Link] the asynchronous main function
main().To schedule the greet function for each name concurrently, use [Link]().Run
the main asynchronous function using asyncio in the if __name__ == “__main__”:
[Link](main()).

import asyncio
async def greet(name):
await [Link](1)
print(name)
async def main():
await [Link](greet("Geeks"), greet("For"), greet("Geeks"))
# If in a Jupyter notebook or IPython environment:
import nest_asyncio
nest_asyncio.apply()
if __name__ == "__main__":
asyncio.create_task(main())

Output:
Geeks
For
Geeks
Queue in Python
Last Updated : 09 Jul, 2024

Like a stack, the queue is a linear data structure that stores items in a First In First Out
(FIFO) manner. With a queue, the least recently added item is removed first. A good example
of a queue is any queue of consumers for a resource where the consumer that came first is
served first.
Operations associated with queue are:
Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an
Overflow condition – Time Complexity : O(1)
Dequeue: Removes an item from the queue. The items are popped in the same order in
which they are pushed. If the queue is empty, then it is said to be an Underflow
condition – Time Complexity : O(1)
Front: Get the front item from queue – Time Complexity : O(1)
Rear: Get the last item from queue – Time Complexity : O(1)

Implement a Queue in Python


There are various ways to implement a queue in Python. This article covers the
implementation of queue using data structures and modules from Python library. Python
Queue can be implemented by the following ways:
list
[Link]
[Link]
Implementation using list
List is a Python’s built-in data structure that can be used as a queue. Instead of
enqueue() and dequeue(), append() and pop() function is used. However, lists are quite
slow for this purpose because inserting or deleting an element at the beginning requires
shifting all of the other elements by one, requiring O(n) time.
The code simulates a queue using a Python list. It adds elements ‘a’, ‘b’, and ‘c’ to the
queue and then dequeues them, resulting in an empty queue at the end. The output
shows the initial queue, elements dequeued (‘a’, ‘b’, ‘c’), and the queue’s empty state.
Python
queue = []
[Link]('a')
[Link]('b')
[Link]('c')
print("Initial queue")
print(queue)
print("\nElements dequeued from queue")
print([Link](0))
print([Link](0))
print([Link](0))
print("\nQueue after removing elements")
print(queue)
Output:
Initial queue
['a', 'b', 'c']
Elements dequeued from queue
a
b
c
Queue after removing elements
[]

Implementation using [Link]


Queue in Python can be implemented using deque class from the collections module.
Deque is preferred over list in the cases where we need quicker append and pop operations
from both the ends of container, as deque provides an O(1) time complexity for append and
pop operations as compared to list which provides O(n) time complexity.
Instead of enqueue and deque, append() and popleft() functions are used.
The code uses a deque from the collections module to represent a queue. It appends ‘a’, ‘b’,
and ‘c’ to the queue and dequeues them with [Link](), resulting in an empty queue.
Uncommenting [Link]() after the queue is empty would raise an IndexError. The code
demonstrates queue operations and handles an empty queue scenario.

from collections import deque


q = deque()
[Link]('a')
[Link]('b')
[Link]('c')
print("Initial queue")
print(q)
print("\nElements dequeued from the queue")
print([Link]())
print([Link]())
print([Link]())

print("\nQueue after removing elements")


print(q)
Output:

Initial queue
deque(['a', 'b', 'c'])
Elements dequeued from the queue
a
b
c
Queue after removing elements
deque([])
Implementation using [Link]
Queue is built-in module of Python which is used to implement a queue.
[Link](maxsize) initializes a variable to a maximum size of maxsize. A maxsize
of zero ‘0’ means a infinite queue. This Queue follows FIFO rule.
There are various functions available in this module:
maxsize – Number of items allowed in the queue.
empty() – Return True if the queue is empty, False otherwise.
full() – Return True if there are maxsize items in the queue. If the queue was initialized
with maxsize=0 (the default), then full() never returns True.
get() – Remove and return an item from the queue. If queue is empty, wait until an item
is available.
get_nowait() – Return an item if one is immediately available, else raise QueueEmpty.
put(item) – Put an item into the queue. If the queue is full, wait until a free slot is
available before adding the item.
put_nowait(item) – Put an item into the queue without blocking. If no free slot is
immediately available, raise QueueFull.
qsize() – Return the number of items in the queue.
Example: This code utilizes the Queue class from the queue module. It starts with an empty
queue and fills it with ‘a’, ‘b’, and ‘c’. After dequeuing, the queue becomes empty, and ‘1’ is
added. Despite being empty earlier, it remains full, as the maximum size is set to 3. The code
demonstrates queue operations, including checking for fullness and emptiness.
from queue import Queue
q = Queue(maxsize = 3)
print([Link]())
[Link]('a')
[Link]('b')
[Link]('c')
print("\nFull: ", [Link]())
print("\nElements dequeued from the queue")
print([Link]())
print([Link]())
print([Link]())
print("\nEmpty: ", [Link]())
[Link](1)
print("\nEmpty: ", [Link]())
print("Full: ", [Link]())
Output:
0
Full: True
Elements dequeued from the queue
a
b
c
Empty: True
Empty: False
Full: False
What Is a Thread
The [Link] class represents a thread of execution in Python.
There are two main ways to use a Thread; they are:
Execute a target function in a new thread.
Extend the Thread class and override run().
Run a Target Function in New Thread
The [Link] class can execute a target function in another thread.
This can be achieved by creating an instance of the [Link] class and
specifying the target function to execute via the target keyword.
The thread can then be started by calling the start() function and it will execute the
target function in another thread.
For example:
# a target function that does something
def work()
# do something...

# create a thread to execute the work() function


thread = Thread(target=work)
# start the thread
[Link]()
If the target function takes arguments, they can be specified via the args argument that
takes a tuple or the kwargs argument that takes a dictionary.
For example:
1 ...
2 # create a thread to execute the work() function
3 thread = Thread(target=work, args=(123,))
The target task function is useful for executing one-off ad hoc tasks that probably don’t
interact with external state other than passed-in arguments and do not return a value
Extend the Thread Class
The [Link] class can be extended for tasks that may involve multiple functions and
maintain state.
This can be achieved by extending the [Link] class and overriding the run() function.
The overridden run() function is then executed when the start() function of the thread is called.
For example:
# define a custom thread
class CustomThread([Link]):
# custom run function
def run():
# do something...

# create the custom thread


thread = CustomThread()
# start the thread
[Link]()

Overriding the [Link] class offers more flexibility than calling a target function. It
allows the object to have multiple functions and to have object member variables for storing
state.
Extending the [Link] class is suited for longer-lived tasks and perhaps services
within an application.
What Is a Process
The [Link] class represents an instance of the Python interpreter for
running code.
There are two main ways to use a Process; they are:
Execute a target function in a new process.
Extend the Process class and override run().
Run a Target Function in New Process
The [Link] class can execute a target function in another process.
This can be achieved by creating an instance of the [Link] class and
specifying the target function to execute via the target keyword.
The process can then be started by calling the start() function and it will execute the target
function in a new child process.
For example:
# a target function that does something
def work()
# do something...

# protect entry point


if __name__ == '__main__':
# create a process to execute the work() function
process = Process(target=work)
# start the process
[Link]()

If the target function takes arguments, they can be specified via the args argument that takes a
tuple or the kwargs argument that takes a dictionary.
For example:
1 ...
2 # create a process to execute the work() function
3 process = Process(target=work, args=(123,))
The target task function is useful for executing one-off ad hoc tasks that probably don’t
interact with external state other than passed-in arguments and do not return a value
Extend the Process Class
The [Link] class can be extended for tasks that may involve multiple
functions and maintain state.
This can be achieved by extending the [Link] class and overriding
the run() function. The overridden run() function is then executed when the start() function of
the process is called.
For example:

# define a custom process


class CustomProcess([Link]):
# custom run function
def run():
# do something...

# protect entry point


if __name__ == '__main__':
# create the custom process
process = CustomProcess()
# start the process
[Link]()
Overriding the Process class offers more flexibility than calling a target function. It allows the
object to have multiple functions and to have object member variables for storing state in the
child process.

How to Print Pattern in Python


In Python, for loop is used to print the various patterns. Printing the various patterns are
most common asked programming questions in the interview. The multiple for loops are used
to print the patterns where the first outer loop is used to print the number of rows, and the inner
loop is used to print the number of columns. Most of the patterns use the following concepts.

o The outer loop to print the number of rows.


o The inner loops to print the number of columns.
o The variable to print whitespace according to the required place in Python.

In this tutorial, we will discuss a few common patterns.

Print Pyramid, Star, and diamond pattern in Python

In this section, we will learn the common pyramid patterns.

Pattern - 1: Simple pyramid pattern


Example -

# Simple Python program to print the Simple pyramid pattern


n = int(input("Enter the number of rows"))
# Here, we are declaring the integer variable to store the input rows
# Here, we are declaring an outer loop to handle number of rows
for i in range(0, n):
# Here, we are declaring an inner loop to handle number of columns
# Here, the values are changing according to outer loop
for j in range(0, i + 1):
# Here, we are declaring a for loop for printing stars
print("* ", end="")
# Here, we are giving the ending line after each row
print()

Output:

Enter the number of rows: 5


*
**
***
****
*****

Explanation:

In the above code, we have initialized the n variable to enter the number of rows for the pattern.
We entered n = 5, the range of outer for loop will be 0 to 4.

o The iteration of the inner for loop depends on the outer loop. The inner loop is
responsible to print the number of columns.
o In the first iteration, the value of i is 0, and it increased by 1, so it becomes 0+1, now
inner loop iterated first time and print one star(*).
o In the second iteration, the value of i is 1 and it increased by 1, so it becomes 1+1, now
inner loop iterated two times and print two-star (*).
o The end argument prevents to jump into another line. It will printer the star until the
loop is valid.
o The last print statement is responsible for ending the line after each row.
PubSub Model in Python
The publish/subscribe (pub/sub) model is a messaging pattern in which
publishers send messages to a message broker, and subscribers express interest in
receiving certain messages. The message broker is responsible for delivering the
messages to the subscribed clients.

Publishers provide messages to a message broker using the publish/subscribe


(pub/sub) model, and subscribers indicate their interest in receiving particular messages.
Delivering the messages to the clients who have subscribed is the responsibility of the
message broker.

Publishers and subscribers are separated in the pub/sub paradigm, so they can
communicate without being aware of one another’s existence. Because publishers and
subscribers can be added or removed without affecting others, this enables a more
flexible and scalable system.
Message queues, event buses, and topic-based publish/subscribe systems are just a few
of the technologies that can be used to construct pub/sub systems. They are frequently
employed in event-driven, distributed, and microservices designs.
In this tutorial, we are going to learn by example, how to implement pub/sub in Python.
Topics in Pub/Sub :
In a publish/subscribe system, topics are used to categorize messages and allow
subscribers to express interest in specific types of messages.
In a topic-based publish/subscribe system, publishers send messages to specific topics,
and subscribers express interest in one or more topics. The message broker is
responsible for delivering the messages to the subscribed clients.
For example, In a news publishing system, there may be topics for different categories
of news, such as politics, sports, and entertainment. Subscribers can express interest in
receiving messages on specific topics, such as only sports and entertainment. When a
publisher sends a message on the sports topic, it will be delivered to all subscribers
interested in that topic
.
Using topics allows for more fine-grained control over the messages that are
delivered to subscribers, as they can choose to receive only the messages that are
relevant to them. It also allows for a more scalable system, as publishers and subscribers
do not need to be aware of each other’s specific identities.

Events in pub/sub :
Events are messages that are published by a publisher and delivered to subscribed
clients. An event is typically a notification of something that has happened or is about to
happen. It can contain data about the event, such as the event type, a description, and any
relevant details. In an event-driven architecture, events are used to trigger actions or
behaviours in other parts of the system. For example, an event might be used to notify a
service that a new user has signed up, or that a payment has been processed. The service can
then respond to the event by performing some action, such as sending a welcome email or
updating a database. Using events allows for a more flexible and scalable system, as publishers
and subscribers do not need to be directly coupled and can communicate asynchronously. It
also allows for a more decoupled and modular system, as components can respond to events
without the need to be aware of the specific identities of the publishers.

Event Bus :
An event bus is a messaging system that allows publishers to send events to subscribers.
It is a type of publish/subscribe system that is commonly used in event-driven architectures.
In an event bus, events are published to a central message broker, which is responsible for
delivering the events to the subscribed clients. Subscribers express interest in receiving events
by registering with the event bus and specifying a list of events that they want to receive.

You might also like