Unit I: Basics of Python Programming
1. Introduction to Python
Python is an interpreted, high-level programming language designed to emphasize code
readability and simplicity. It supports multiple programming paradigms, including object-
oriented, procedural, and functional programming. Python uses dynamic typing and memory
management, allowing developers to write programs faster. Python's large standard library
offers solutions for tasks such as string manipulation, web development, and file I/O. Its
straightforward syntax, combined with a supportive community, makes it one of the most
popular programming languages today.
Code Example:
python
Copy code
# Simple program to print a message
print("Welcome to Python Programming")
2. Variables, Expressions, and Statements
Variables in Python store data, while expressions combine variables and operators to compute
results. A statement in Python is an instruction executed by the interpreter, such as assigning
values or printing output. Python supports various data types, such as integers, floats, and
strings. Expressions use operators like + (addition), - (subtraction), and * (multiplication),
among others. Variables don’t need to be declared with a specific type due to Python's dynamic
typing.
Code Example:
python
Copy code
# Assigning values to variables
a=5
b = 3.2
c = "Hello"
# Expression using variables
result = a + b
print(result) # Output: 8.2
3. Conditionals and Iteration
Conditionals allow decision-making based on Boolean expressions (True or False). if, elif, and
else statements control which code block runs. Python also supports iteration using loops. for
loops iterate over sequences like lists, and while loops execute as long as a condition remains
True. The break and continue statements can alter loop behavior, stopping or skipping
iterations.
Code Example:
python
Copy code
# Conditional example
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is 5 or less")
# Iteration using for loop
for i in range(3):
print(i) # Output: 0, 1, 2
4. Functions and Recursion
Functions are reusable blocks of code that perform specific tasks. They take inputs
(parameters) and return results using the return statement. Python also supports recursion,
where a function calls itself to solve a problem in smaller parts. Recursion requires a base case
to avoid infinite loops.
Code Example:
python
Copy code
# Function to calculate the factorial of a number
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(5)) # Output: 120
Unit II: Working with Data Structures
1. Strings
Strings are sequences of characters in Python and are immutable, meaning they cannot be
changed after creation. You can perform various operations on strings, like concatenation,
slicing, and using methods such as .upper(), .lower(), and .find(). Strings are iterable, which
allows you to loop over their characters easily.
Code Example:
python
Copy code
# String operations
s = "Hello, World"
print(s[0:5]) # Output: Hello (Slicing)
print(s.upper()) # Output: HELLO, WORLD (Uppercase)
2. Lists
Lists in Python are mutable collections that store multiple items in a single variable. Lists can
contain elements of different types and support operations like indexing, slicing, and modifying
the list. Common methods include .append(), .remove(), and .sort(). Lists are dynamic and can
grow or shrink as needed during runtime.
Code Example:
python
Copy code
# Creating a list and performing operations
my_list = [1, 2, 3, 4, 5]
my_list.append(6) # Adding an element
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
3. Tuples and Dictionaries
Tuples are immutable sequences, typically used to group related data. Dictionaries are
unordered collections of key-value pairs, used to store data in an efficient lookup structure.
Tuples are accessed by indexing, while dictionary values are accessed using keys. Dictionaries
provide methods like .keys() and .values() for retrieving data.
Code Example:
python
Copy code
# Tuple example
t = (1, 2, 3)
print(t[1]) # Output: 2
# Dictionary example
my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"]) # Output: Alice
Unit III: Advanced Topics
1. Classes and Objects
Classes are blueprints for creating objects in Python. An object is an instance of a class,
containing attributes (data) and methods (functions). Classes in Python support object-
oriented programming (OOP) principles like encapsulation and inheritance. The __init__()
method initializes the object, and self is used to access class attributes within methods.
Code Example:
python
Copy code
# Creating a class and an object
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(f"{self.name} is barking")
dog = Dog("Buddy", "Labrador")
dog.bark() # Output: Buddy is barking
2. Object-Oriented Programming Terminology
Object-Oriented Programming (OOP) in Python revolves around concepts like inheritance,
method overriding, and encapsulation. Inheritance allows a class to inherit attributes and
methods from another class. Method overriding occurs when a subclass provides a specific
implementation of a method in its superclass. Encapsulation hides data to prevent external
modification, promoting data security and consistency.
Code Example:
python
Copy code
# Inheritance and method overriding
class Animal:
def sound(self):
print("Some sound")
class Dog(Animal):
def sound(self):
print("Bark")
dog = Dog()
dog.sound() # Output: Bark
3. Files and Exceptions
Python makes working with files easy using built-in functions like open(), read(), and write(). You
can handle errors gracefully using exceptions with the try, except, and finally blocks. Common
exceptions include FileNotFoundError and ValueError. The with statement is commonly used for
safe file handling, automatically closing files when operations are complete.
Code Example:
python
Copy code
# File handling with exception
try:
with open("example.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("File not found")