Python Programming
Python Programming
Features in Python:
In this section we will see what are the features of Python programming language:
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
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
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.
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.
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.
Python is also an Integrated language because we can easily integrate Python with
other languages like C, C++, etc.
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.
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.
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.
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.
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."
The installer will now proceed with the installation process. You'll see a progress bar
indicating the status. This might take a few minutes.
Once the installation is complete, you should see a "Setup was successful" message.
Click "Close" to exit the installer.
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
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
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
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.
Lists in Python can be created by just placing the sequence inside the square
brackets[].
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.
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.
In order to access the tuple items refer to the index number. Use the index operator
[ ] to access an item in a tuple.
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.
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.
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
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.
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’.
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().
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
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.
Example (Python):
Creating a User-defined Module (my_math.py):
Python
def add(x, y):
return x + y
Adding new data and functions is not easy. Adding new data and function is easy.
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
Mutable (elements
Mutable Immutable
Mutability must be immutable)
No duplicates
Allows duplicates Allows duplicates
Duplicates allowed
Supports
Supports indexing and
Not supported indexing and
slicing
Indexing slicing
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
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:
Python
def greet():
"""Prints a simple greeting message."""
print("Hello there!")
Python
def greet_by_name(name):
"""Greets the person with the given name."""
print(f"Hello, {name}!")
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
Python
def power(base, exponent=2):
"""Calculates the power of a base to a given exponent (default is
2)."""
return base ** exponent
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)
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
if __name__ == "__main__":
thread1 = threading.Thread(target=task, args=("One", 2))
thread2 = threading.Thread(target=task, args=("Two", 1))
thread1.start()
thread2.start()
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:
Python
import multiprocessing
import time
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()
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
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
Isolation Less isolation (threads share memory) Better isolation (processes are separate)
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.