Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1 views

Python Programming

Python is a dynamic, high-level, open-source programming language that supports both object-oriented and procedural programming. Key features include its ease of use, readability, large community support, and a rich standard library. The document also outlines the installation process, data types, and object-oriented programming concepts in Python.

Uploaded by

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

Python Programming

Python is a dynamic, high-level, open-source programming language that supports both object-oriented and procedural programming. Key features include its ease of use, readability, large community support, and a rich standard library. The document also outlines the installation process, data types, and object-oriented programming concepts in Python.

Uploaded by

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

Python and it’s features

Python is a dynamic, high-level, free open source, and interpreted programming


language. It supports object-oriented programming as well as procedural-oriented
programming. In Python, we don’t need to declare the type of variable because it is
a dynamically typed language. For example, x = 10 Here, x can be anything such
as String, int, etc. In this article we will see what characteristics describe the python
programming language.

Features in Python:

In this section we will see what are the features of Python programming language:

1. Free and Open Source

Python language is freely available at the official website and you can download it
from the given download link below click on the Download
Python keyword. Download Python Since it is open-source, this means that source
code is also available to the public. So you can download it, use it as well as share
it.

2. Easy to code

Python is a high-level programming language. Python is very easy to learn the


language as compared to other languages like C, C#, Javascript, Java, etc. It is
very easy to code in the Python language and anybody can learn Python basics in
a few hours or days. It is also a developer-friendly language.

3. Easy to Read

As you will see, learning Python is quite simple. As was already established,
Python’s syntax is really straightforward. The code block is defined by the
indentations rather than by semicolons or brackets.

4. Object-Oriented Language

One of the key features of Python is Object-Oriented programming . Python


supports object-oriented language and concepts of classes, object encapsulation,
etc.

5. GUI Programming Support

Graphical User interfaces can be made using a module such as PyQt5, PyQt4,
wxPython, or Tk in Python. PyQt5 is the most popular option for creating graphical
apps with Python.
6. High-Level Language
Python is a high-level language. When we write programs in Python, we do not
need to remember the system architecture, nor do we need to manage the
memory.

7. Large Community Support

Python has gained popularity over the years. Our questions are constantly
answered by the enormous StackOverflow community. These websites have
already provided answers to many questions about Python, so Python users can
consult them as needed.

8. Easy to Debug

Excellent information for mistake tracing. You will be able to quickly identify and
correct the majority of your program’s issues once you understand how
to interpret Python’s error traces. Simply by glancing at the code, you can
determine what it is designed to perform.

9. Python is a Portable language

Python language is also a portable language. For example, if we have Python code
for Windows and if we want to run this code on other platforms such as Linux, Unix,
and Mac then we do not need to change it, we can run this code on any platform.

10. Python is an Integrated language

Python is also an Integrated language because we can easily integrate Python with
other languages like C, C++, etc.

11. Interpreted Language:

Python is an Interpreted Language because Python code is executed line by line at


a time. like other languages C, C++, Java, etc. there is no need to compile Python
code this makes it easier to debug our code. The source code of Python is
converted into an immediate form called bytecode.

12. Large Standard Library

Python has a large standard library that provides a rich set of modules and
functions so you do not have to write your own code for every single thing. There
are many libraries present in Python such as regular expressions, unit-testing, web
browsers, etc.
13. Dynamically Typed Language

Python is a dynamically-typed language. That means the type (for example- int,
double, long, etc.) for a variable is decided at run time not in advance because of
this feature we don’t need to specify the type of variable.

14. Frontend and backend development

With a new project py script, you can run and write Python codes in HTML with the
help of some simple tags <py-script>, <py-env>, etc. This will help you do frontend
development work in Python like javascript. Backend is the strong forte of Python
it’s extensively used for this work cause of its frameworks like Django and Flask.

15. Allocating Memory Dynamically

In Python, the variable data type does not need to be specified. The memory is
automatically allocated to a variable at runtime when it is given a value. Developers
do not need to write int y = 18 if the integer value 15 is set to y. You may just type
y=18.

Python installation Process

It's a pretty straightforward process. Here are the steps:

1. Download the Python Installer:

 Open your web browser and go to the official Python website:


https://www.python.org/downloads/windows/
 You'll see links for the latest Python releases. It's generally recommended to
download the latest stable version. Look for the button that says something like
"Download Python 3.x.x" (where 'x.x.x' represents the specific version number).
 Click on that button to download the installer executable file (it will likely have a
.exe extension).

2. Run the Installer:

 Once the download is complete, locate the downloaded .exe file (it's usually in your
"Downloads" folder).
 Double-click on the .exe file to run the Python installer.

3. Important: Customize Installation (and Add Python to PATH):

 When the installer window opens, you'll see two important checkboxes at the bottom:
o "Install launcher for all users (recommended)": It's generally a good idea
to leave this checked.
o "Add Python 3.x to PATH": Make sure you check this box! Adding
Python to your system's PATH environment variable allows you to run Python
from the command prompt or PowerShell without having to navigate to the
Python installation directory every time.
 You can choose between "Install Now" (which installs Python with default settings)
or "Customize installation" (which gives you more control over the installation
location and optional features).
o For most users, "Install Now" with the "Add Python 3.x to PATH" box
checked is sufficient and recommended.
o If you choose "Customize installation," you can:
 Change the installation location.
 Select optional features to install (like pip, the package installer for
Python, which is usually checked by default and highly
recommended).
 Choose whether to associate .py files with the Python launcher.
 After making your selections, click either "Install Now" or "Install."

4. Wait for Installation to Complete:

 The installer will now proceed with the installation process. You'll see a progress bar
indicating the status. This might take a few minutes.

5. Setup Was Successful:

 Once the installation is complete, you should see a "Setup was successful" message.
 Click "Close" to exit the installer.

6. Verify the Installation:

 Now, let's make sure Python was installed correctly and that it's in your PATH.
 Open the Command Prompt (search for "cmd" in the Start Menu and press Enter) or
PowerShell (search for "powershell" in the Start Menu and press Enter).
 Type the following command and press Enter:

Bash

python --version

 If Python is installed correctly and added to your PATH, you should see the Python
version number displayed (e.g., Python 3.12.3).
 You can also try running the pip command to verify that the package installer is also
working:

Bash

pip --version

You should see information about the pip version and its location.
Python Data Types

Python Data types are the classification or categorization of data items. It


represents the kind of value that tells what operations can be performed on a
particular data. Since everything is an object in Python programming, Python data
types are classes and variables are instances (objects) of these classes. The
following are the standard or built-in data types in Python:
 Numeric – int, float, complex
 Sequence Type – string, list, tuple
 Mapping Type – dict
 Boolean – bool
 Set Type – set, frozenset
 Binary Types – bytes, bytearray, memoryview

1. Numeric Data Types in Python

The numeric data type in Python represents the data that has a numeric value. A numeric
value can be an integer, a floating number, or even a complex number. These values are
defined as Python int, Python float and Python complex classes in Python.
 Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an
integer value can be.
 Float – This value is represented by the float class. It is a real number with a floating-
point representation. It is specified by a decimal point. Optionally, the character e or E
followed by a positive or negative integer may be appended to specify scientific notation.
 Complex Numbers – A complex number is represented by a complex class. It is
specified as (real part) + (imaginary part)j . For example – 2+3j

2. Sequence Data Types in Python

The sequence Data Type in Python is the ordered collection of similar or different
Python data types. Sequences allow storing of multiple values in an organized and
efficient fashion. There are several sequence data types of Python:
 Python String
 Python List
 Python Tuple

String Data Type

Python Strings are arrays of bytes representing Unicode characters. In Python,


there is no character data type Python, a character is a string of length one. It is
represented by str class.
Strings in Python can be created using single quotes, double quotes or even triple
quotes. We can access individual characters of a String using index.
List Data Type

Lists are just like arrays, declared in other languages which is an ordered collection
of data. It is very flexible as the items in a list do not need to be of the same type.

Creating a List in Python

Lists in Python can be created by just placing the sequence inside the square
brackets[].

Access List Items

In order to access the list items refer to the index number. In Python, negative
sequence indexes represent positions from the end of the array. Instead of having
to compute the offset as in List[len(List)-3], it is enough to just write List[-3].
Negative indexing means beginning from the end, -1 refers to the last item, -2
refers to the second-last item, etc.

Tuple Data Type

Just like a list, a tuple is also an ordered collection of Python objects. The only
difference between a tuple and a list is that tuples are immutable. Tuples cannot be
modified after it is created.

Creating a Tuple in Python

In Python Data Types, tuples are created by placing a sequence of values


separated by a ‘comma’ with or without the use of parentheses for grouping the
data sequence. Tuples can contain any number of elements and of any datatype
(like strings, integers, lists, etc.).

Access Tuple Items

In order to access the tuple items refer to the index number. Use the index operator
[ ] to access an item in a tuple.

3. Boolean Data Type in Python

Python Data type with one of the two built-in values, True or False. Boolean objects that are
equal to True are truthy (true), and those equal to False are falsy (false). However non-
Boolean objects can be evaluated in a Boolean context as well and determined to be true or
false. It is denoted by the class bool.
Example: The first two lines will print the type of the boolean values True and False, which
is <class ‘bool’>. The third line will cause an error, because true is not a valid keyword in
Python. Python is case-sensitive, which means it distinguishes between uppercase and
lowercase letters.

4. Set Data Type in Python

In Python Data Types, Set is an unordered collection of data types that is iterable,
mutable, and has no duplicate elements. The order of elements in a set is
undefined though it may consist of various elements.

Create a Set in Python

Sets can be created by using the built-in set() function with an iterable object or a
sequence by placing the sequence inside curly braces, separated by
a ‘comma’. The type of elements in a set need not be the same, various mixed-up
data type values can also be passed to the set.
Example: The code is an example of how to create sets using different types of
values, such as strings , lists , and mixed values

Access Set Items

Set items cannot be accessed by referring to an index, since sets are unordered
the items have no index. But we can loop through the set items using a for loop, or
ask if a specified value is present in a set, by using the in the keyword.

5. Dictionary Data Type

A dictionary in Python is a collection of data values, used to store data values like a
map, unlike other Python Data Types that hold only a single value as an element, a
Dictionary holds a key: value pair. Key-value is provided in the dictionary to make it
more optimized. Each key-value pair in a Dictionary is separated by a colon : ,
whereas each key is separated by a ‘comma’.

Create a Dictionary in Python

Values in a dictionary can be of any datatype and can be duplicated, whereas keys
can’t be repeated and must be immutable. The dictionary can also be created by
the built-in function dict().

Accessing Key-value in Dictionary

In order to access the items of a dictionary refer to its key name. Key can be used
inside square brackets. Using get() method we can access the dictionary
elements.
Python OOPs Concepts

Object Oriented Programming is a fundamental concept in Python,


empowering developers to build modular, maintainable, and scalable
applications. By understanding the core OOP principles (classes, objects,
inheritance, encapsulation, polymorphism, and abstraction), programmers
can leverage the full potential of Python OOP capabilities to design
elegant and efficient solutions to complex problems.
OOPs is a way of organizing code that uses objects and classes to
represent real-world entities and their behavior. In OOPs, object has
attributes thing that has specific data and can perform certain actions
using methods.

OOPs Concepts in Python


 Class in Python
 Objects in Python
 Polymorphism in Python
 Encapsulation in Python
 Inheritance in Python
 Data Abstraction in Python

The four main principles of Object-Oriented Programming (OOP)


are Encapsulation, Abstraction, Inheritance, and
Polymorphism. These principles help organize code, make it reusable,
and facilitate collaboration among objects.

Encapsulation: This principle bundles data (attributes) and the methods


that operate on that data into a single unit (a class), controlling access and
protecting the data from outside interference.

Abstraction: This principle hides complex implementation details and


exposes only the essential features of an object, simplifying interaction with
the object and making the code easier to understand.
Inheritance: This principle allows a new class (child class) to inherit
properties and methods from an existing class (parent class), promoting
code reusability and creating hierarchical relationships between classes.
Polymorphism: This principle allows objects of different classes to be
treated as objects of a common type, enabling flexible and dynamic
behavior and promoting code flexibility.
Python List
In Python, a list is a built-in dynamic sized array (automatically grows and
shrinks). We can store all types of items (including another list) in a list. A
list may contain mixed type of items, this is possible because a list mainly
stores references at contiguous locations and actual items maybe stored
at different locations.
 List can contain duplicate items.
 List in Python are Mutable. Hence, we can modify, replace or delete
the items.
 List are ordered. It maintain the order of elements based on how they
are added.
 Accessing items in List can be done directly using their position
(index), starting from 0.

Modules in Python
In programming, a module is a self-contained unit of code, often a file
containing Python definitions and statements (like functions, classes, or
variables). Modules are used to organize related code into a reusable
package, making code easier to understand, maintain, and reuse across
different projects. In hardware, a module is a component designed for easy
addition or removal from a system, like a RAM stick.

Types of Modules (Python Example):


 Built-in Modules:
These come pre-installed with Python and provide a wide range of functionalities
(e.g., math for mathematical operations, os for operating system
interactions, random for generating random numbers).
 User-defined Modules:
These are created by the programmer to encapsulate specific functionality and
make it reusable.

Example (Python):
Creating a User-defined Module (my_math.py):
Python
def add(x, y):
return x + y

def subtract(x, y):


return x - y

Using the User-defined Module:


Python
# Import the module
import my_math

# Use functions from the module


result_add = my_math.add(5, 3)
result_subtract = my_math.subtract(10, 4)

print("Add result:", result_add) # Output: Add result: 8


print("Subtract result:", result_subtract) # Output: Subtract result: 6

Procedural Oriented Programming Object-Oriented Programming

In object-oriented programming, the


In procedural programming, the program is
program is divided into small parts
divided into small parts called functions.
called objects.

Procedural programming follows a top- Object-oriented programming follows


down approach. a bottom-up approach.

Object-oriented programming has access


There is no access specifier in procedural
specifiers like private, public, protected,
programming.
etc.

Adding new data and functions is not easy. Adding new data and function is easy.

Procedural programming does not have


Object-oriented programming provides
any proper way of hiding data so it is less
data hiding so it is more secure.
secure.

In procedural programming, overloading is Overloading is possible in object-oriented


not possible. programming.
Procedural Oriented Programming Object-Oriented Programming

In object-oriented programming, the


In procedural programming, there is no
concept of data hiding and inheritance is
concept of data hiding and inheritance.
used.

In procedural programming, the function is In object-oriented programming, data is


more important than the data. more important than function.

Procedural programming is based on Object-oriented programming is based on


the unreal world. the real world.

Procedural programming is used for Object-oriented programming is used for


designing medium-sized programs. designing large and complex programs.

Procedural programming uses the concept Object-oriented programming uses the


of procedure abstraction. concept of data abstraction.

Code reusability absent in procedural Code reusability present in object-oriented


programming, programming.

Examples: C, FORTRAN, Pascal, Basic,


Examples: C++, Java, Python, C#, etc.
etc.

Difference between List VS Set VS Tuple in


Python
In Python, Lists, Sets and Tuples store collections but differ in behavior. Lists are
ordered, mutable and allow duplicates, suitable for dynamic data. Sets are
unordered, mutable and unique, while Tuples are ordered, immutable and allow
duplicates, ideal for fixed data.

List in Python

A List is a collection of ordered, mutable elements that can hold a variety of data
types. Lists are one of the most commonly used data structures in Python due to
their flexibility and ease of use.
Key Characteristics:
 Mutable: Elements can be modified after creation.
 Ordered: Maintains the order of elements.
 Allows Duplicates: Can have multiple occurrences of the same value.
 Heterogeneous: Can store different data types.

Set in Python

A Set is an unordered collection of unique elements. Sets are primarily used when
membership tests and eliminating duplicate values are needed.
Key Characteristics:
 Mutable: Elements can be added or removed.
 Unordered: Does not maintain the order of elements.
 Unique Elements: Duplicate values are automatically removed.
 Heterogeneous: Can store different data types.

Tuple in Python

A Tuple is an ordered, immutable collection of elements. Tuples are often used


when data should not be modified after creation.
Key Characteristics:
 Immutable: Once created, elements cannot be modified.
 Ordered: Maintains the order of elements.
 Allows Duplicates: Can contain duplicate values.
 Heterogeneous: Can store different data types.

Key Differences Between Lists, Set and Tuple


Feature List Set Tuple

Mutable (elements
Mutable Immutable
Mutability must be immutable)

Ordering Ordered Unordered Ordered

No duplicates
Allows duplicates Allows duplicates
Duplicates allowed

Supports
Supports indexing and
Not supported indexing and
slicing
Indexing slicing

Slower for Faster membership


Faster than lists
Performance membership tests tests

When frequent When


When uniqueness is
modifications are immutability is
needed
Use Case required required
Functions in python
Functions in Python! They are the building blocks of well-organized and reusable code.
Think of a function as a named block of code that performs a specific task. You can define a
function once and then call it multiple times from different parts of your program, without
having to rewrite the same code over and over again. This makes your code cleaner, more
readable, and easier to maintain.

Defining a Function:

You define a function in Python using the def keyword, followed by the function name,
parentheses (), and a colon :. The code block that the function executes is indented below
the def line.

Syntax:

Python
def function_name(parameters):
"""Optional docstring to describe what the function does"""
# Code to be executed within the function
# ...
return [expression] # Optional return statement

 def: Keyword that indicates the start of a function definition.


 function_name: A unique name you give to your function (following Python's
naming conventions).
 parameters: Optional placeholders for values that you can pass into the function
when you call it. These are listed inside the parentheses and are comma-separated. A
function can have zero or more parameters.
 :: Colon that marks the end of the function definition line.
 docstring: An optional string literal enclosed in triple quotes ("""Docstring goes
here""") that provides a description of what the function does, its parameters, and
what it returns. It's good practice to include docstrings for your functions.
 # Code to be executed within the function: The indented block of code that
performs the function's task.
 return [expression]: An optional statement that sends a value back to the caller of
the function. If there's no return statement, or if return is used without an
expression, the function returns None.

Calling a Function:

To execute the code inside a function, you need to "call" it by using its name followed by
parentheses (). If the function has parameters, you provide the corresponding values 1
(arguments) inside the parentheses.

1. open.openclass.ai

open.openclass.ai
Examples:

1. Function with no parameters and no return value:

Python
def greet():
"""Prints a simple greeting message."""
print("Hello there!")

greet() # Calling the function


# Output: Hello there!

2. Function with one parameter:

Python
def greet_by_name(name):
"""Greets the person with the given name."""
print(f"Hello, {name}!")

greet_by_name("Alice") # Calling the function with an argument


greet_by_name("Bob")
# Output:
# Hello, Alice!
# Hello, Bob!

3. Function with multiple parameters and a return value:

Python
def add(num1, num2):
"""Adds two numbers and returns the sum."""
sum_result = num1 + num2
return sum_result

result = add(5, 3) # Calling the function and storing the return value
print(f"The sum is: {result}") # Output: The sum is: 8

4. Function with a default parameter value:

Python
def power(base, exponent=2):
"""Calculates the power of a base to a given exponent (default is
2)."""
return base ** exponent

square = power(5) # Uses the default exponent of 2


cube = power(3, 3) # Overrides the default exponent
print(f"5 squared is: {square}") # Output: 5 squared is: 25
print(f"3 cubed is: {cube}") # Output: 3 cubed is: 27

5. Function returning multiple values:

Python
def divide(dividend, divisor):
"""Divides two numbers and returns the quotient and remainder."""
quotient = dividend // divisor
remainder = dividend % divisor
return quotient, remainder # Returns a tuple

result_tuple = divide(10, 3)
print(f"Quotient and remainder: {result_tuple}") # Output: Quotient and
remainder: (3, 1)

q, r = divide(15, 4) # Unpacking the returned tuple


print(f"Quotient: {q}, Remainder: {r}") # Output: Quotient: 3, Remainder:
3

Benefits of Using Functions:

 Modularity: Functions break down complex programs into smaller, manageable


units.
 Reusability: Once defined, a function can be called multiple times, reducing code
duplication.
 Readability: Using meaningful function names makes the code easier to understand.
 Maintainability: Changes or bug fixes within a function only need to be done in one
place.
 Abstraction: Functions hide the underlying implementation details, allowing you to
focus on what the function does rather than how it does it.

Understanding and utilizing functions effectively is a crucial step in becoming a proficient


Python programmer. They are essential for writing clean, efficient, and maintainable code.

Multithreading and Multiprocessing


Alright, let's dive into the concepts of multithreading and multiprocessing in Python. Both are
techniques used to achieve parallelism, allowing your program to perform multiple tasks
seemingly simultaneously, which can significantly improve performance for certain types of
workloads. However, they operate in fundamentally different ways and have their own
strengths and weaknesses.

Understanding Concurrency vs. Parallelism:

Before we delve into the specifics, it's helpful to understand the distinction between
concurrency and parallelism:

 Concurrency: Deals with managing multiple tasks within the same timeframe. The tasks may
not be executing at the exact same instant, but they make progress by taking turns (like
rapidly switching between them). Think of it as juggling multiple balls; you're handling each
one, but not all at the same moment.
 Parallelism: Involves the actual simultaneous execution of multiple tasks on multiple
processing units (like CPU cores). This is like having multiple jugglers, each handling one or
more balls at the same time.

1. Multithreading:
 Concept: Multithreading achieves concurrency by creating multiple threads within a single
process. A thread is the smallest unit of execution within a process. These threads share the
same memory space of the parent process.
 How it works in Python: Python's standard library provides the threading module to work
with threads. You can create and manage multiple threads that can execute different parts of
your code concurrently.
 Example:

Python
import threading
import time

def task(name, delay):


print(f"Thread {name}: Starting")
time.sleep(delay)
print(f"Thread {name}: Finished after {delay} seconds")

if __name__ == "__main__":
thread1 = threading.Thread(target=task, args=("One", 2))
thread2 = threading.Thread(target=task, args=("Two", 1))

thread1.start()
thread2.start()

thread1.join() # Wait for thread1 to complete


thread2.join() # Wait for thread2 to complete

print("All threads finished")

In this example, two threads are created to run the task function with different names and
delays. thread1.start() and thread2.start() initiate the execution of these threads.
thread1.join() and thread2.join() make the main program wait until these threads
have completed their execution.

 Global Interpreter Lock (GIL): A crucial aspect of multithreading in CPython (the most
common Python implementation) is the Global Interpreter Lock (GIL). The GIL is a mutex (a
locking mechanism) that protects access to Python objects, preventing multiple native threads
from executing Python bytecode at the same time within a single process.
 Implications of the GIL:
o CPU-bound tasks: For tasks that are heavily CPU-intensive (doing a lot of calculations),
multithreading in CPython often doesn't provide significant speedups on multi-core
processors because only one thread can hold the GIL and execute Python bytecode at any
given time. The other threads spend most of their time waiting to acquire the lock. In such
cases, the concurrency might improve responsiveness (e.g., keeping the UI from freezing),
but not necessarily the overall execution time.
o I/O-bound tasks: Multithreading can be very effective for I/O-bound tasks (waiting for
network requests, file operations, user input, etc.). While one thread is waiting for I/O, the
GIL can be released, allowing another thread to run. This improves the overall throughput of
the program.
 When to use Multithreading:
o I/O-bound operations where threads can release the GIL while waiting for external
operations.
o Improving the responsiveness of an application (e.g., keeping the user interface active while
background tasks are running).
o Managing multiple concurrent, independent operations within a single process.

2. Multiprocessing:

 Concept: Multiprocessing overcomes the limitations of the GIL by creating multiple


independent processes. Each process has its own Python interpreter and its own memory
space. This allows for true parallelism on multi-core systems, as multiple processes can
execute Python bytecode simultaneously on different cores.
 How it works in Python: Python's multiprocessing module allows you to create and
manage multiple processes.
 Example:

Python
import multiprocessing
import time

def task_process(name, delay):


print(f"Process {name}: Starting")
time.sleep(delay)
print(f"Process {name}: Finished after {delay} seconds")

if __name__ == "__main__":
process1 = multiprocessing.Process(target=task_process,
args=("One", 2))
process2 = multiprocessing.Process(target=task_process,
args=("Two", 1))

process1.start()
process2.start()

process1.join() # Wait for process1 to complete


process2.join() # Wait for process2 to complete

print("All processes finished")

This example is very similar to the multithreading example, but it uses


multiprocessing.Process instead of threading.Thread. Each process runs
independently with its own memory space.

 Inter-Process Communication (IPC): Since processes have separate memory spaces, sharing
data between them is more complex than between threads in the same process. The
multiprocessing module provides various mechanisms for IPC, such as:
o Pipes and Queues: For sending messages between processes.
o Shared Memory: For allowing processes to access a shared memory region (requires careful
synchronization).
 When to use Multiprocessing:
o CPU-bound tasks that can benefit from true parallelism on multi-core systems.

o Tasks that need to be isolated from each other (if one process crashes, it's less likely to affect
others).
o When you want to fully utilize multiple CPU cores for computationally intensive operations.

Summary Table:
Feature Multithreading Multiprocessing

Process Multiple threads within one process Multiple independent processes

Memory Shared memory space Separate memory spaces

GIL (CPython) Affected by the GIL Not affected by the GIL

CPU-bound tasks Limited parallelism due to GIL True parallelism on multiple cores

I/O-bound tasks Can be very effective Also effective, but higher overhead

Complexity Generally simpler to implement More complex due to IPC requirements

Overhead Lower (thread creation is lighter) Higher (process creation is heavier)

Isolation Less isolation (threads share memory) Better isolation (processes are separate)

Use Cases I/O-bound, responsiveness CPU-bound, true parallelism, isolation

Choosing Between Multithreading and Multiprocessing:

The choice between multithreading and multiprocessing depends largely on the nature of the
task you need to parallelize:

 If your task is primarily I/O-bound (waiting for external resources), multithreading can be a
good and often simpler option to improve concurrency.
 If your task is CPU-bound (doing a lot of computation), multiprocessing is generally the
better choice to achieve true parallelism and utilize multiple CPU cores effectively, bypassing
the GIL limitation.

Keep in mind that multiprocessing has a higher overhead due to the creation and management
of separate processes and the need for explicit inter-process communication.

Python also offers higher-level abstractions for concurrency and parallelism, such as the
concurrent.futures module (which can use either threads or processes from a pool) and
asynchronous programming (asyncio), which provide more structured ways to handle
concurrent operations. However, understanding the underlying concepts of multithreading
and multiprocessing is crucial for making informed decisions about how to parallelize your
Python code.

You might also like