Python
Python
The Python interpreter is an environment that reads Python code and executes it. Interactive
mode (also called the REPL, Read-Eval-Print Loop) allows you to type and execute Python
code one line at a time, which is useful for testing small code snippets and learning.
Data Types
● Variables are used to store data. You create a variable by assigning a value to it, e.g., x
= 5.
● Expressions are combinations of variables, literals, and operators that Python
evaluates, e.g., 3 + 4 * 2.
● Statements perform actions, e.g., print(x) or x = 10.
Tuple Assignment
Precedence of Operators
1. Parentheses ()
2. Exponents **
3. Multiplication and division *, /, //, %
4. Addition and subtraction +, -
Comments
Comments help document code. In Python, single-line comments start with #, while multi-line
comments can use triple quotes (''' or """).
Modules and Functions
● Modules are files containing Python definitions and statements. You can import modules
to use functions defined in them, e.g., import math.
● Functions are reusable blocks of code that perform a specific task.
Defining Functions
def greet(name):
print(f"Hello, {name}!")
Flow of Execution
The flow of execution is the order in which Python executes statements. Functions are executed
in the order they are called.
Parameters are variables in the function definition, while arguments are the actual values
passed to the function.
Illustrative Programs
x, y = 5, 10
x, y = y, x
print(x, y) # Output: 10 5
values = [1, 2, 3, 4]
distance^2=(x2−x1)^2+(y2−y1)^2
import math
UNIT 2
Conditionals
1. Boolean Values and Operators: Boolean values are True and False. Common
operators include:
○ Logical operators: and, or, not
○ Comparison operators: ==, !=, <, >, <=, >=
2. Conditional Statements:
○ if: Executes a block of code if a condition is True.
○ if-else: Provides an alternative block to execute if the condition is False.
○ if-elif-else: Allows checking multiple conditions in sequence.
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
Iteration
n=5
while n > 0:
print(n)
n -= 1
for i in range(5):
print(i)
Functions
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
Strings
2. Immutability: Strings cannot be changed after creation. Any modification creates a new
string.
Lists
● Lists are mutable sequences that can store various data types. They support indexing,
slicing, and common operations like .append(), .remove(), .pop().
Illustrative Programs
guess = n / 2.0
return guess
while b != 0:
a, b = b, a % b
return a
print(gcd(48, 18)) # Output: 6
3. Exponentiation (Recursive)
if exp == 0:
return 1
elif exp % 2 == 0:
else:
def sum_array(numbers):
return sum(numbers)
5. Linear Search
if value == target:
return index
return -1
print(linear_search([1, 3, 5, 7], 5)) # Output: 2
if arr[mid] == target:
return mid
low = mid + 1
else:
high = mid - 1
return -1
These examples illustrate key concepts of control flow, functions, strings, and lists in Python.
Each program demonstrates how Python’s control structures can be used to implement efficient
algorithms. Let me know if you need further clarification on any specific part!
UNIT -3
Lists in Python
Lists are mutable, ordered collections that can hold various data types.
1. List Operations
Accessing Elements: Use indexing to access individual elements. Negative indexing starts
from the end of the list.
my_list = [10, 20, 30, 40]
print(my_list[0]) # Output: 10
print(my_list[-1]) # Output: 40
list2 = [4, 5]
2. List Slices
Slicing lets you extract a part of a list by specifying a start and end index.
my_list = [1, 2, 3, 4, 5]
3. List Methods
4. List Loop
print(element)
5. Mutability
my_list = [1, 2, 3]
6. Aliasing
Aliasing happens when you assign one list to another. Both variables will point to the same list,
so changes in one will affect the other.
list1 = [1, 2, 3]
list2 = list1
list2[0] = 100
7. Cloning Lists
To avoid aliasing, you can create a shallow copy of the list using slicing or the copy() method.
list2 = list1[:] # or list1.copy()
8. List Parameters
When a list is passed to a function, it’s passed by reference, meaning the function can modify
the original list.
def modify_list(lst):
lst[0] = 'modified'
my_list = [1, 2, 3]
modify_list(my_list)
Tuples in Python
Tuples are similar to lists but are immutable, meaning their elements cannot be changed.
1. Tuple Assignment
Tuples are created using parentheses, and you can access elements by indexing.
my_tuple = (10, 20, 30)
def min_max(lst):
return min(lst), max(lst)
Dictionaries in Python
Dictionaries store data as key-value pairs and provide methods to add, remove, and modify
entries.
# Accessing values
# Removing keys
# With a condition
1. Sorting
Python provides sorted() for a sorted copy and sort() to sort in place.
my_list = [3, 1, 4, 2]
●
2. Searching
Use the in operator for simple checks or linear/binary search algorithms for complex cases.
if 3 in my_list:
print("Found 3!")
Binary Search (assuming a sorted list) can be implemented using a loop or the bisect module
for efficiency.
import bisect
my_list = [1, 2, 3, 4, 5]
● index = bisect.bisect_left(my_list, 3)
UNIT -4
In Python, classes are blueprints for creating objects. Classes define the properties (attributes)
and behaviors (methods) that the objects created from them will have.
class Dog:
An instance is an individual object of a class. Each instance can have unique attribute values.
2. Why OOP?
● Code Reusability: Classes and methods can be reused across different parts of an
application.
● Encapsulation: Attributes and methods are bundled together in objects, hiding
unnecessary details.
● Inheritance: New classes can inherit the properties and methods of existing classes.
● Polymorphism: Different classes can be used interchangeably if they implement similar
methods.
3. Inheritance
Inheritance allows a class (subclass) to inherit attributes and methods from another class
(superclass). It enables code reuse and helps in building a hierarchy of classes.
Example of Inheritance
Let’s create a Dog superclass and have a WorkingDog subclass inherit from it.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
def do_job(self):
● WorkingDog inherits attributes (name, breed) and methods (bark()) from Dog.
● WorkingDog has an additional attribute job and a method do_job().
# Base class
class Animal:
self.name = name
self.species = species
def make_sound(self):
# Subclass - Dog
class Dog(Animal):
self.breed = breed
def make_sound(self):
# Subclass - Cat
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name, "Cat")
self.color = color
def make_sound(self):
In this hierarchy:
super().__init__(name, "Bird")
self.wing_span = wing_span
def make_sound(self):
def fly(self):
By calling make_sound() on each instance, we see how each subclass defines its own version
of the method:
print(animal.make_sound())
Copy code
Summary
With these foundations, you can create complex and structured applications, improving
readability, reusability, and maintainability.
UNIT -5
Python makes file operations straightforward. We commonly work with text files, reading and
writing their contents.
Opening Files
Reading Files
content = file.read()
Writing Files
file.write("Hello, World!")
2. Format Operator
The format operator (%) and newer .format() method are used for inserting values into
strings.
name = "Alice"
age = 25
Command-line arguments are parameters passed to the program when it starts. Python’s
sys.argv list stores these arguments.
import sys
if len(sys.argv) > 1:
bash
5. Handling Exceptions
try:
content = file.read()
except FileNotFoundError:
except Exception as e:
else:
finally:
● Modules: A module is a Python file with functions and classes. Importing modules is
done with the import statement.
import math
For example:
# - `module1.py`
# To use:
Illustrative Programs
def word_count(filename):
try:
content = file.read()
return len(words)
except FileNotFoundError:
filename = "example.txt"
A file copying program reads from a source file and writes to a target file.
try:
content = src.read()
dest.write(content)
except FileNotFoundError:
except Exception as e:
source_file = "example.txt"
destination_file = "copy_of_example.txt"
copy_file(source_file, destination_file)
In this program:
Summary
This guide covered file operations, exception handling, and using modules and packages in
Python, with illustrative programs for word counting and file copying. These are essential tasks
for building robust, error-resistant programs in Python. Let me know if you'd like more examples
or details on any specific topic!