Python
Python
1.INTRODUCTION TO PYTHON...........................................................................................1
2.PYTHON BASICS..................................................................................................................3
3.OPERATORS IN PYTHON....................................................................................................5
5.FUNCTIONS IN PYTHON..................................................................................................15
6.1 Lists................................................................................................................................18
6.2 Tuples.............................................................................................................................19
6.3 Sets.................................................................................................................................19
6.4 Dictionaries....................................................................................................................20
7.FILE HANDLING................................................................................................................22
8.EXCEPTION HANDLING..................................................................................................25
9.OBJECT-ORIENTED PROGRAMMING............................................................................30
9.6 Inheritance......................................................................................................................33
9.7 Polymorphism................................................................................................................34
Python is widely used in various domains, including web development, data science, artificial
intelligence, automation, and more. Its extensive standard library and support for third-party
packages make it a powerful tool for solving complex problems efficiently. Due to its
versatility, Python is one of the most popular programming languages in the world today.
Another significant feature of Python is its portability. Python programs can run on various
operating systems, such as Windows, macOS, and Linux, without modification. Additionally,
Python has automatic memory management, reducing the need for manual memory allocation
and deallocation, which simplifies coding and improves performance.
Automation is another area where Python excels. With simple scripts, tasks like file handling,
data extraction, and web scraping can be automated, saving time and effort. Python is also
1
commonly used in cybersecurity, network programming, embedded systems, and even game
development, showcasing its versatility in the software industry.
For writing and running Python programs, various integrated development environments
(IDEs) are available, such as PyCharm, VS Code, and Jupyter Notebook. The default Python
IDLE (Integrated Development and Learning Environment) is also a simple option for
beginners. Setting up a proper development environment ensures a smooth coding experience
and enables better debugging and execution of Python scripts.
Python scripts typically start with a print() statement or variable declarations. Statements are
written in a single line, and comments are added using the # symbol. Multi-line comments
can be written using triple quotes (''' or """). Python follows a dynamic typing approach,
meaning variables do not require explicit type declarations, making code development faster
and more flexible.
2
2.PYTHON BASICS
Python provides various ways to execute scripts, including IDEs like PyCharm and VS Code,
text editors like Notepad++, and Jupyter Notebooks for interactive computing. Regardless of
the environment, Python’s easy-to-use syntax makes it a preferred choice for beginners and
professionals alike.
Strings (str) – Textual data enclosed in single or double quotes, such as "Hello, World!".
Complex Numbers (complex) – Numbers with real and imaginary parts, such as 2 + 3j.
Python also allows type conversion between these data types using functions like int(),
float(), and str(), making it flexible for various operations.
3
For user input, Python uses the input() function, which reads input as a string. If numerical
operations are needed, the input must be converted using int() or float(). Handling
input/output efficiently is crucial for building interactive Python programs.
Explicit conversion, or type casting, is done using functions like int(), float(), str(), and
bool(). This is useful when performing operations that require specific data types, such as
mathematical calculations or string manipulations. Understanding type conversion helps
avoid errors and ensures data consistency in programs.
4
3.OPERATORS IN PYTHON
Operators are symbols that perform operations on variables and values. Python supports
various types of operators to handle mathematical, logical, and bitwise operations.
For example:
a = 10
b=3
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333
Floor Division: 3
Modulus: 1
Exponentiation: 1000
5
The // operator performs floor division, meaning it rounds down the result to the nearest
whole number. The ** operator raises the number to the power of another number.
For example:
x=5
y = 10
x is equal to y: False
For example:
a = True
6
b = False
print("a or b:", a or b)
a and b: False
a or b: True
not a: False
For example:
a = 5 (Binary: 0101)
b = 3 (Binary: 0011)
print("Bitwise OR:", a | b)
print("Bitwise XOR:", a ^ b)
Bitwise AND: 1
7
Bitwise OR: 7
Bitwise XOR: 6
Bitwise NOT of a: -6
Left Shift: 10
Right Shift: 2
For example:
x = 10
x += 5 (Equivalent to x = x + 5)
x -= 3 (Equivalent to x = x - 3)
x *= 2 (Equivalent to x = x * 2)
x /= 4 (Equivalent to x = x / 4)
x %= 3 (Equivalent to x = x % 3)
x **= 2 (Equivalent to x = x ** 2)
If the initial value of x is 10, the output after each operation will be:
x = 15
8
x = 12
x = 24
x = 6.0
x = 0.0
x = 0.0
For example:
my_list = [1, 2, 3, 4, 5]
print(3 in my_list)
True
True
For example:
b=a
print(a is b)
print(a is not c)
9
The output will be:
True
True
10
4.CONTROL FLOW STATEMENTS
Control flow statements determine the sequence in which instructions are executed in a
program. Python provides conditional statements, loops, and loop control mechanisms to
control the flow of execution.
For example:
num = 10
if num > 0:
print("Positive number")
Positive number
num = -5
if num > 0:
print("Positive number")
else:
print("Negative number")
Output:
Negative number
num = 0
if num > 0:
11
print("Positive number")
print("Negative number")
else:
print("Zero")
Output:
Zero
count = 1
print("Count:", count)
count += 1
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
A for loop is used to iterate over sequences like lists, tuples, and strings:
print("Iteration:", i)
Output:
12
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
if i == 5:
break
print(i)
Output:
The continue statement skips the current iteration and moves to the next one:
if i == 3:
continue
print(i)
Output:
13
2
if i == 3:
pass
print(i)
Output:
14
5.FUNCTIONS IN PYTHON
Functions in Python allow code reuse and modular programming. Python supports different
types of function arguments, including positional arguments, keyword arguments, default
arguments, arbitrary positional arguments (*args), and arbitrary keyword arguments
(**kwargs).
Example:
greet("Alice", 25)
Output:
If the number of arguments in the function call does not match the function definition, an
error occurs.
Example:
greet("Bob")
greet("Charlie", 22)
Output:
15
Hello Bob You are 18 years old.
Example:
greet(age=30, name="David")
Output:
Using keyword arguments improves readability and avoids confusion in argument order.
Example:
def sum_numbers(*numbers):
total = sum(numbers)
print("Sum:", total)
sum_numbers(1, 2, 3, 4, 5)
Output:
Sum: 15
The function can take any number of arguments, and they are stored in a tuple.
16
5.5 Arbitrary Keyword Arguments (kwargs)
The **kwargs parameter allows a function to accept any number of keyword arguments as a
dictionary.
Example:
def person_info(**info):
Output:
name : Eve
age : 28
This is useful when a function must accept a varying number of named parameters.
17
6.DATA STRUCTURES IN PYTHON
Data structures help in organizing and managing data efficiently. Python provides several
built-in data structures that allow storing and manipulating data in various ways. The primary
data structures in Python include:
Lists
Tuples
Sets
Dictionaries
6.1 Lists
A list is an ordered, mutable collection that allows duplicate elements. Lists are defined using
square brackets [ ].
Example:
print(fruits)
Output:
Adding elements:
fruits.append("mango")
Removing elements:
fruits.remove("banana")
18
print(fruit)
6.2 Tuples
A tuple is an ordered, immutable collection that allows duplicate elements. Tuples are defined
using parentheses ( ).
Example:
print(numbers)
Output:
Tuples are useful when data should not be modified after creation.
print(numbers[1]) # Outputs: 20
Tuples can be used as dictionary keys and are more memory-efficient than lists.
6.3 Sets
A set is an unordered collection of unique elements. Sets are defined using curly braces { }.
Example:
unique_numbers = {1, 2, 3, 4, 5, 1, 2}
print(unique_numbers)
Output:
{1, 2, 3, 4, 5}
Sets do not allow duplicate values and provide fast membership testing.
Adding elements:
unique_numbers.add(6)
Removing elements:
19
unique_numbers.remove(3)
6.4 Dictionaries
A dictionary is an unordered collection of key-value pairs. Dictionaries are defined using
curly braces { } with keys and values separated by colons :.
Example:
print(student)
Output:
Accessing values:
student["grade"] = "A"
Example:
print(text)
String operations:
20
print(text[0:5]) # Outputs: Hello
21
7.FILE HANDLING
File handling allows reading, writing, and manipulating files in Python. Python provides
built-in functions to work with files using the open() function. The key operations in file
handling include:
Writing to a File
Appending to a File
Syntax:
Example:
The close() method is used to free up system resources after file operations.
Example:
content = file.read()
print(content)
22
file.close()
Example:
print(line.strip())
file.close()
Example:
file.write("Hello, Python!")
file.close()
Hello, Python!
Example:
file.close()
Hello, Python!
23
7.5 Working with File Modes
Python provides different file modes:
file.write("New Content")
print(file.read())
file.close()
24
8.EXCEPTION HANDLING
Exception handling in Python allows programs to deal with unexpected errors and prevent
crashes. Python provides a robust mechanism to handle runtime errors using the try-except
block. The key concepts in exception handling include:
Introduction to Exceptions
Custom Exceptions
Example of an exception:
a = 10
b=0
Output:
25
To handle such errors, we use try-except blocks.
Example:
try:
a = 10
b=0
print(a / b)
except ZeroDivisionError:
Output:
If an exception occurs in the try block, control jumps to except, preventing a crash.
Example:
try:
print(x / y)
except ZeroDivisionError:
except ValueError:
26
If the user enters "abc", a ValueError occurs, and the respective message is displayed.
Example:
try:
except ValueError:
else:
print("Operation successful!")
Example:
try:
content = file.read()
print(content)
except FileNotFoundError:
finally:
27
8.6 Raising Exceptions with raise
The raise keyword allows us to generate custom exceptions.
Example:
def check_age(age):
print("Access granted.")
try:
check_age(16)
except ValueError as e:
print("Error:", e)
Output:
Example:
class NegativeNumberError(Exception):
pass
def check_positive(num):
if num < 0:
print("Number is positive.")
try:
28
check_positive(-5)
except NegativeNumberError as e:
print("Error:", e)
Output:
29
9.OBJECT-ORIENTED PROGRAMMING
Introduction to OOP
Inheritance
Polymorphism
Python allows creating classes and objects, making programs more modular and reusable.
Example:
class Car:
def start(self):
30
print("Car is starting...")
Output:
Car is starting...
Example:
class Person:
self.name = name
self.age = age
def display(self):
p1 = Person("Alice", 25)
p1.display()
Output:
31
9.4 Instance and Class Variables
Instance variables → Defined inside the constructor and unique for each object.
Example:
class Student:
s1 = Student("John")
s2 = Student("Emma")
print(s1.name, s1.school)
print(s2.name, s2.school)
Output:
Example:
32
class BankAccount:
self.__balance += amount
def get_balance(self):
return self.__balance
acc = BankAccount(1000)
acc.deposit(500)
9.6 Inheritance
Inheritance allows a class to acquire properties of another class.
class Animal:
def make_sound(self):
class Dog(Animal):
33
def bark(self):
print("Dog barks")
d = Dog()
d.make_sound()
d.bark()
Output:
Dog barks
9.7 Polymorphism
Polymorphism allows using a single function name for different types.
class Shape:
def area(self):
print("Calculating area...")
class Circle(Shape):
def area(self):
c = Circle()
c.area()
Output:
Area of Circle = π × r²
34
10. MODULES AND PACKAGES
For example, the math module provides mathematical functions like sqrt(), pow(), and
factorial(). To use these functions, one can import the module using import math and call
math.sqrt(16), which returns 4.0. Additionally, Python allows importing specific functions
from a module using the from keyword, such as from math import sqrt, enabling direct use
without prefixing with the module name.
Python also allows aliasing modules using the as keyword. For instance, import mymodule as
mm lets the module be referenced using mm.greet(). Moreover, one can use from mymodule
import greet to directly call greet() without prefixing it with the module name. This flexibility
makes modular programming in Python highly efficient and scalable.
35
module2.py, etc. To use a module from a package, one can write import mypackage.module1
and access its functions as mypackage.module1.function_name().
Namespaces in Python help avoid naming conflicts by ensuring that variable and function
names are unique within different scopes. Python provides different types of namespaces,
including local, global, and built-in namespaces. The globals() and locals() functions can be
used to inspect global and local namespaces, respectively. Understanding packages and
namespaces allows developers to build scalable and organized Python applications.
To check installed packages, the command pip list is used, which displays a list of all
installed packages along with their versions. Updating a package is done using pip install --
upgrade package_name, while removing a package is possible with pip uninstall
package_name. Additionally, developers can use requirements.txt to list dependencies and
install them in bulk using pip install -r requirements.txt, ensuring a smooth package
management workflow.
For example, the os module allows file and directory management with functions like
os.listdir() to list files in a directory and os.remove() to delete a file. The json module helps in
parsing and generating JSON data with functions like json.dumps() and json.loads().
Leveraging the Python Standard Library enables efficient programming without relying on
additional dependencies.
36
11. WORKING WITH NUMPY AND PANDAS
One of the key advantages of NumPy is its ability to handle large datasets efficiently using
optimized C-based implementations. Functions like numpy.array() allow the creation of
arrays, while operations such as numpy.mean(), numpy.sum(), and numpy.dot() enable
efficient numerical computations. The performance of NumPy makes it a fundamental library
for data science, machine learning, and scientific computing.
37
One of the key advantages of Pandas is its ability to handle missing data efficiently using
dropna() and fillna() functions. The read_csv() and read_excel() functions allow easy loading
of datasets, while operations like filtering, grouping, and merging help in data transformation.
The Pandas library is essential for working with structured datasets, making it indispensable
for data science applications.
Data manipulation in Pandas includes indexing, slicing, filtering, and applying functions
using apply(). DataFrames can be modified using functions like add(), drop(), and merge().
The groupby() function is used for aggregating data, while pivot_table() helps in reshaping
data. The ability to perform vectorized operations makes Pandas an efficient tool for handling
large datasets.
Data transformation includes converting data types using astype(), renaming columns with
rename(), and changing index labels with set_index(). Pandas also supports handling
categorical data, applying functions to entire columns, and merging datasets using concat()
and merge(). These capabilities make Pandas a powerful tool for preprocessing real-world
data before performing analysis or machine learning tasks.
38
12. DATABASE CONNECTIVITY IN PYTHON
Python provides various libraries for database connectivity, including sqlite3 for SQLite,
mysql-connector-python for MySQL, and psycopg2 for PostgreSQL. These libraries allow
seamless interaction with databases, enabling developers to execute queries and manage data
efficiently. Using databases in Python applications ensures data persistence, integrity, and
structured storage.
To insert data into a table, use the SQL command "INSERT INTO students (name, age)
VALUES ('Alice', 22)" and execute it with the cursor. To save the changes, call
conn.commit().
To retrieve data from a table, execute "SELECT * FROM students" and use cursor.fetchall()
to fetch all rows. Iterate through the result and print each row.
39
To update data, use "UPDATE students SET age = 23 WHERE name = 'Alice'" and execute
it. Similarly, to delete data, execute "DELETE FROM students WHERE name = 'Alice'".
CRUD operations allow efficient data manipulation within Python programs while ensuring
database integrity.
MySQL supports structured data storage and allows efficient querying and indexing for large-
scale applications. Connection pooling and optimized queries improve performance in
MySQL-based Python applications.
To define a table using SQLAlchemy, import the necessary modules, define a class
representing the table, and specify the column names and data types. Then, use
create_engine() to establish a connection to the database and call
Base.metadata.create_all(engine) to create the table.
40
13. MULTITHREADING AND CONCURRENCY
Python provides the threading module for implementing multithreading and the
multiprocessing module for running multiple processes. However, due to Python’s Global
Interpreter Lock (GIL), true parallel execution using threads is limited. Therefore,
multithreading is best suited for I/O-bound tasks, while multiprocessing is ideal for CPU-
bound tasks.
To create a thread in Python, use the Thread class from the threading module. Define a
function that performs a specific task and pass it as a target to Thread(). Start the thread using
the start() method.
Threads in Python share memory, allowing efficient task execution but requiring
synchronization mechanisms like locks to prevent race conditions and ensure data
consistency.
A lock restricts multiple threads from modifying a shared resource simultaneously. Use the
acquire() method before accessing shared data and release() after completing the operation.
This prevents data inconsistency and unpredictable behavior in multithreaded applications.
41
Other synchronization techniques include semaphores, condition variables, and event objects,
which help coordinate thread execution based on specific conditions.
To use multiprocessing, create a Process object and specify a function as the target. Start the
process using the start() method, and use join() to ensure all processes complete before the
main program exits.
The async and await keywords define and run asynchronous functions. These functions pause
execution while waiting for external operations (e.g., network requests) and resume once the
operation is complete. This improves efficiency in applications that handle multiple I/O-
bound operations simultaneously, such as web scraping, network communication, and
database queries.
Asynchronous programming is widely used in web frameworks like FastAPI and Tornado,
ensuring responsive and scalable applications.
42