UNIT– I
Introduction: History of Python Programming Language, Thrust Areas of Python,
Installing Anaconda Python Distribution, Installing and Using Jupyter Notebook. Parts of
Python Programming Language: Identifiers, Keywords, Statements and Expressions,
Variables, Operators, Precedence and Associativity, Data Types, Indentation,
Comments, Reading Input, Print Output, Type Conversions, the type () Function and Is
Operator, Dynamic and Strongly Typed Language. Control Flow Statements: if
statement, if-else statement, if...elif…else, Nested if statement, while Loop, for Loop,
continue and break Statements, Exception Handling: Catching Exceptions Using try
and except Statement.
Sample Experiments:
1. Write a program to find the largest element among three Numbers.
2. Write a Program to display all prime numbers within an interval
3. Write a program to swap two numbers without using a temporary variable.
4. Demonstrate the following Operators in Python with suitable examples.
i) Arithmetic Operators ii) Relational Operators iii) Assignment Operators
iv) Logical Operators v) Bitwise Operators vi) Ternary Operator vii) Membership
Operators viii) Identity Operators
5. Write a program to add and multiply complex numbers
6. Write a program to print a multiplication table of a given number.
Python Programming Language
Introduction
History of Python
Python was created in the late 1980s by Guido van Rossum and first released in 1991.
Designed for readability and simplicity, Python supports multiple programming
paradigms, including procedural, object-oriented, and functional programming. Its
extensive standard library and community support have contributed to its widespread
adoption in various fields such as web development, data analysis, artificial intelligence,
and scientific computing.
Thrust Areas of Python
Python is commonly used in:
Web Development: Frameworks like Django and Flask facilitate rapid
development and clean design.
Data Science: Libraries such as Pandas, NumPy, and Matplotlib offer powerful
data manipulation and visualization capabilities.
Machine Learning: TensorFlow, Keras, and Scikit-learn provide tools for building
machine learning models.
Automation/Scripting: Python is ideal for automating tasks and writing scripts
for system administration.
Game Development: Frameworks like Pygame enable the creation of interactive
games.
Installing Anaconda Python Distribution
Anaconda is a popular distribution for Python, especially for data science and machine
learning. It includes Python, the Conda package manager, and numerous pre-installed
libraries.
Steps to Install Anaconda:
1. Download: Visit the Anaconda website and download the installer for your
operating system.
2. Installation: Follow the installation prompts to set up Anaconda on your
machine.
3. Environment Setup: Use Anaconda Navigator or the command line to create
and manage environments.
Installing and Using Jupyter Notebook
Jupyter Notebook is an open-source web application for creating and sharing documents
that contain live code, equations, visualizations, and narrative text.
Steps to Use Jupyter Notebook:
1. Launch Jupyter: Open Anaconda Navigator and select Jupyter Notebook, or run
jupyter notebook from the command line.
2. Creating Notebooks: Create new notebooks and start coding in Python
interactively.
Parts of Python Programming Language
1. Identifiers
Identifiers are names given to variables, functions, and classes. They must start with a
letter or underscore.
2. Keywords
Keywords are reserved words in Python that have special meaning (e.g., if, else, for,
while).
3. Statements and Expressions
Statements perform actions, while expressions compute values.
4. Variables
Variables are containers for storing data values.
5. Operators
Operators are symbols that perform operations (e.g., arithmetic, comparison).
6. Precedence and Associativity
Precedence determines the order of operations in expressions, while associativity
determines how operators of the same precedence are grouped.
7. Data Types
Python has various built-in data types, including:
Integers
Floats
Strings
Lists
Tuples
Dictionaries
Sets
8. Indentation
Python uses indentation to define blocks of code. Consistent indentation is crucial for
code readability.
9. Comments
Comments are used to explain code. Use # for single-line comments and triple quotes ('''
or """) for multi-line comments.
10. Reading Input
The input() function is used to read user input from the console.
11. Print Output
The print() function displays output to the console.
12. Type Conversions
Python provides functions like int(), float(), and str() to convert between data types.
13. The type() Function
The type() function returns the type of an object, helping to identify its data type.
14. is Operator
The is operator checks if two references point to the same object in memory.
15. Dynamic and Strongly Typed Language
Python is dynamically typed, meaning variable types can change at runtime. It is also
strongly typed, ensuring that operations are only performed on compatible types.
Control Flow Statements
1. If Statement
The if statement executes a block of code if a specified condition is true.
2. If-Else Statement
The if-else statement allows for an alternative block of code to execute when the
condition is false.
3. If...Elif...Else
This structure allows for multiple conditions to be checked sequentially.
4. Nested If Statement
Nested if statements are used to check additional conditions within another if statement.
5. While Loop
The while loop repeatedly executes a block of code as long as a specified condition is
true.
6. For Loop
The for loop iterates over a sequence (like a list or string) and executes a block of code
for each item.
7. Continue and Break Statements
Continue: Skips the current iteration and moves to the next.
Break: Exits the loop immediately.
Exception Handling
Catching Exceptions Using try and except
Python provides try and except blocks to handle exceptions gracefully, allowing the
program to continue running even when an error occurs.
try:
# Code that may cause an exception
except ExceptionType:
# Code to handle the exception
Solutions for sample experiments:
1. Write a program to find the largest element among three Numbers.
# Program to find the largest among three numbers
num1 = 10
num2 = 20
num3 = 15
if num1 >= num2 and num1 >= num3:
largest = num1
elif num2 >= num1 and num2 >= num3:
largest = num2
else:
largest = num3
print(f"The largest number among {num1}, {num2}, and {num3} is: {largest}")
output: The largest number among 10, 20, and 15 is: 20
2. Write a Program to display all prime numbers within an interval
# Program to display all prime numbers within an interval
start_interval = 10
end_interval = 50
for num in range(start_interval, end_interval + 1):
if num <= 1:
continue
is_prime = True
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=' ')
print()
output:11 13 17 19 23 29 31 37 41 43 47
3. Write a program to swap two numbers without using a temporary variable.
# Program to swap two numbers without using a temporary variable
a=5
b = 10
print(f"Before swap: a = {a}, b = {b}")
a=a+b
b=a-b
a=a-b
print(f"After swap: a = {a}, b = {b}")
output:
Before swap: a = 5, b = 10
After swap: a = 10, b = 5
4. Demonstrate the following Operators in Python with suitable examples.
i) Arithmetic Operators ii) Relational Operators iii) Assignment Operators
iv) Logical Operators v) Bitwise Operators vi) Ternary Operator vii) Membership
Operators viii) Identity Operators
# Demonstrating different types of operators in Python
# i) Arithmetic Operators
a = 10
b=5
print(f"Arithmetic Operators: {a} + {b} = {a + b}, {a} - {b} = {a - b}, {a} * {b} = {a * b}, {a} / {b} =
{a / b}")
# ii) Relational Operators
print(f"Relational Operators: {a} > {b} = {a > b}, {a} < {b} = {a < b}")
# iii) Assignment Operators
c=a
c += b # c = c + b
print(f"Assignment Operators: c = {c}")
# iv) Logical Operators
print(f"Logical Operators: True and False = {True and False}, True or False = {True or
False}")
# v) Bitwise Operators
print(f"Bitwise Operators: {a} & {b} = {a & b}, {a} | {b} = {a | b}")
# vi) Ternary Operator
max_value = a if a > b else b
print(f"Ternary Operator: max_value = {max_value}")
# vii) Membership Operators
list_items = [1, 2, 3, 4, 5]
print(f"Membership Operators: 3 in list_items = {3 in list_items}")
# viii) Identity Operators
print(f"Identity Operators: {a} is {b} = {a is b}, {a} is not {b} = {a is not b}")
output:
Arithmetic Operators: 10 + 5 = 15, 10 - 5 = 5, 10 * 5 = 50, 10 / 5 = 2.0
Relational Operators: 10 > 5 = True, 10 < 5 = False
Assignment Operators: c = 15
Logical Operators: True and False = False, True or False = True
Bitwise Operators: 10 & 5 = 0, 10 | 5 = 15
Ternary Operator: max_value = 10
Membership Operators: 3 in list_items = True
Identity Operators: 10 is 5 = False, 10 is not 5 = True
5. Write a program to add and multiply complex numbers
# Program to add and multiply complex numbers
complex1 = 2 + 3j
complex2 = 4 + 5j
addition = complex1 + complex2
multiplication = complex1 * complex2
print(f"Addition of complex numbers: {complex1} + {complex2} = {addition}")
print(f"Multiplication of complex numbers: {complex1} * {complex2} = {multiplication}")
output:
Addition of complex numbers: (2+3j) + (4+5j) = (6+8j)
Multiplication of complex numbers: (2+3j) * (4+5j) = (-7+22j)
6. Write a program to print a multiplication table of a given number.
# Program to print a multiplication table of a given number
number = 5
print(f"Multiplication Table for {number}:")
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
output:
Multiplication Table for 5:
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
UNIT– II
Functions: Built-in functions, Commonly Used Modules, Function Definition and Calling
the function, return Statement and void Function, Scope and Lifetime of Variables,
Default Parameters, Keyword Arguments, *args and **kwargs, Command Line
Arguments.
Strings:
Creating and Storing Strings, Basic String Operations, Accessing Characters in String by
Index Number,
Functions
Built-in Functions
Python provides a variety of built-in functions that perform common tasks. Examples
include:
print(): Outputs data to the console.
len(): Returns the length of an object.
type(): Returns the type of an object.
range(): Generates a sequence of numbers.
Commonly Used Modules
Python has many standard modules that provide additional functionality:
math: Mathematical functions (e.g., [Link](), [Link]()).
datetime: Working with dates and times.
random: Generate random numbers.
os: Interacting with the operating system.
Function Definition and Calling the Function
Functions are defined using the def keyword:
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Calling the function
output:
Hello, Alice!
Return Statement and Void Function
A function can return a value using the return statement. A void function does not return
anything:
def add(a, b):
return a + b
def print_message():
print("This is a void function.")
result = add(5, 3)
print(result) # Outputs: 8
print_message() # Outputs: This is a void function.
output:
8
This is a void function.
Scope and Lifetime of Variables
Local Variables: Defined within a function, only accessible inside that function.
Global Variables: Defined outside all functions, accessible throughout the
module.
Default Parameters
Functions can have default parameter values:
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Outputs: Hello, Guest!
greet("Bob") # Outputs: Hello, Bob!
output:Hello, Guest!
Hello, Bob!
Keyword Arguments
Keyword arguments allow you to specify arguments by name:
def describe_person(name, age):
print(f"{name} is {age} years old.")
describe_person(age=30, name="Alice") # Order does not matter
ouput:
Alice is 30 years old.
*args and **kwargs
*args: Allows passing a variable number of non-keyword arguments.
**kwargs: Allows passing a variable number of keyword arguments.
def display(*args, **kwargs):
print("Args:", args)
print("Kwargs:", kwargs)
display(1, 2, 3, name="Alice", age=25)
output:
Args: (1, 2, 3)
Kwargs: {'name': 'Alice', 'age': 25}
Command Line Arguments
Command line arguments can be accessed using the sys module:
Code:
import sys
# Example usage: python [Link] arg1 arg2
print("Command line arguments:", [Link])
ouput:
Command line arguments: ['c:/Users/hp/Desktop/python/concept_functions.py']
Strings
Creating and Storing Strings
Strings can be created using single or double quotes:
string1 = 'Hello'
string2 = "World"
Basic String Operations
Common operations include concatenation and repetition:
greeting = string1 + " " + string2 # Concatenation
repeat = string1 * 3 # Repetition
Accessing Characters in String by Index Number
Strings are indexed starting from 0:
char = string1[1] # 'e'
String Slicing and Joining
Slicing: Extracts a substring.
Joining: Combines elements of a list into a string.
substring = string1[1:4] # 'ell'
joined = " ".join([string1, string2]) # 'Hello World'
String Methods
Python provides various built-in string methods:
lowercase = [Link]() # 'hello'
uppercase = [Link]() # 'WORLD'
length = len(string1) # 5
Formatting Strings
Strings can be formatted using f-strings or the format() method:
name = "Alice"
age = 30
formatted = f"{name} is {age} years old." # f-string
formatted2 = "{} is {} years old.".format(name, age) # format method
Lists
Creating Lists
Lists are created using square brackets:
fruits = ["apple", "banana", "cherry"]
Basic List Operations
Common operations include appending, removing, and accessing elements:
[Link]("orange") # Add to the end
[Link]("banana") # Remove by value
first_fruit = fruits[0] # Access first element
Indexing and Slicing in Lists
Lists can be indexed and sliced similarly to strings:
Built-In Functions Used on Lists
Common list functions include:
len(): Get the number of elements.
max(): Get the largest element.
min(): Get the smallest element.
count = len(fruits)
largest = max(fruits) # Alphabetical order for strings
List Methods
List methods include:
sort(): Sorts the list in place.
reverse(): Reverses the list in place.
[Link]() # Sorts alphabetically
[Link]() # Reverses the order
del Statement
The del statement removes an item or the entire list:
del fruits[1] # Removes the second element
del fruits # Deletes the entire list
Sample Experiments:
7. Write a program to define a function with multiple return values.
8. Write a program to define a function using default arguments.
9. Write a program to find the length of the string without using any library functions.
10. Write a program to check if the substring is present in a given string or not.
11. Write a program to perform the given operations on a list: a) Addition b). Insertion c).
Slicing
12. Write a program to perform any 5 built-in functions by taking any list.
7. Write a program to define a function with multiple return values.
# Program to define a function with multiple return values
def calculate(a, b):
sum_result = a + b
diff_result = a - b
return sum_result, diff_result # Returning multiple values
# Example usage
num1 = 10
num2 = 5
sum_value, diff_value = calculate(num1, num2)
print(f"Sum: {sum_value}, Difference: {diff_value}")
output:
Sum: 15, Difference: 5
8. Function Using Default Arguments
# Program to define a function using default arguments
def greet(name="Guest", message="Welcome!"):
print(f"Hello, {name}! {message}")
# Example usage
greet() # Using default values
greet("Alice") # Using one default value
greet("Bob", "Glad to see you!") # Using both custom values
output:
Hello, Guest! Welcome!
Hello, Alice! Welcome!
Hello, Bob! Glad to see you!
9. Length of a String Without Using Any Library Functions
# Program to find the length of the string without using any library functions
input_string = "Hello, World!"
length = 0
for char in input_string:
length += 1 # Incrementing length for each character
print(f"The length of the string is: {length}")
output:
The length of the string is: 13
10. Check If Substring Is Present in a Given String
# Program to check if the substring is present in a given string
main_string = "Hello, World!"
substring = "World"
if substring in main_string:
print(f"The substring '{substring}' is present in the main string.")
else:
print(f"The substring '{substring}' is not present in the main string.")
output:
The substring 'World' is present in the main string.
11. Perform Operations on a List: Addition, Insertion, Slicing
# Program to perform operations on a list
my_list = [1, 2, 3, 4]
# a) Addition
my_list.append(5) # Adding an element
print("After addition:", my_list)
# b) Insertion
my_list.insert(1, 10) # Inserting 10 at index 1
print("After insertion:", my_list)
# c) Slicing
sliced_list = my_list[1:4] # Slicing elements from index 1 to 3
print("Sliced list:", sliced_list)
output:
After addition: [1, 2, 3, 4, 5]
After insertion: [1, 10, 2, 3, 4, 5]
Sliced list: [10, 2, 3]
12. Perform Any 5 Built-in Functions on a List
# Program to perform 5 built-in functions on a list
numbers = [4, 2, 8, 5, 1]
# 1. Length of the list
length = len(numbers)
print("Length of the list:", length)
# 2. Maximum value
max_value = max(numbers)
print("Maximum value in the list:", max_value)
# 3. Minimum value
min_value = min(numbers)
print("Minimum value in the list:", min_value)
# 4. Sum of all elements
total = sum(numbers)
print("Sum of all elements:", total)
# 5. Sorted list
sorted_list = sorted(numbers)
print("Sorted list:", sorted_list)
output:
Length of the list: 5
Maximum value in the list: 8
Minimum value in the list: 1
Sum of all elements: 20
Sorted list: [1, 2, 4, 5, 8]
UNIT– III
Dictionaries, Tuples, and Sets in Python
Dictionaries
Creating a Dictionary
A dictionary is a mutable, unordered collection of key-value pairs. It is created using curly
braces {} or the dict() function.
# Creating a dictionary
my_dict = {
"name": "Alice",
"age": 25,
"city": "New York"
}
# Alternatively, using dict()
my_dict2 = dict(name="Bob", age=30, city="Los Angeles")
Accessing and Modifying Key
Pairs in Dictionaries
You can access values using their corresponding keys. Modifying values is straightforward
as well.
# Accessing a value
print(my_dict["name"]) # Outputs: Alice
# Modifying a value
my_dict["age"] = 26
print(my_dict) # Outputs: {'name': 'Alice', 'age': 26, 'city': 'New York'}
Built-In Functions Used on Dictionaries
Common built-in functions for dictionaries include:
len(): Returns the number of key-value pairs.
max(), min(): Returns the maximum or minimum key.
# Using built-in functions
print(len(my_dict)) # Outputs: 3
Dictionary Methods
Python provides several useful methods for dictionaries:
keys(): Returns a view object displaying a list of all keys.
values(): Returns a view object displaying a list of all values.
items(): Returns a view object displaying a list of key-value pairs.
print(my_dict.keys()) # Outputs: dict_keys(['name', 'age', 'city'])
print(my_dict.values()) # Outputs: dict_values(['Alice', 26, 'New York'])
print(my_dict.items()) # Outputs: dict_items([('name', 'Alice'), ('age', 26), ('city', 'New York')])
del Statement
The del statement can be used to remove a specific key-value pair or the entire dictionary.
del my_dict["city"] # Removes the key 'city'
print(my_dict) # Outputs: {'name': 'Alice', 'age': 26}
del my_dict # Deletes the entire dictionary
Tuples and Sets
Creating Tuples
A tuple is an immutable, ordered collection of elements. Tuples can be created using
parentheses () or the tuple() function.
# Creating a tuple
my_tuple = (1, 2, 3)
another_tuple = tuple([4, 5, 6])
Basic Tuple Operations
Tuples support basic operations such as indexing, slicing, and concatenation.
# Indexing
print(my_tuple[1]) # Outputs: 2
# Slicing
print(my_tuple[0:2]) # Outputs: (1, 2)
# Concatenation
combined_tuple = my_tuple + another_tuple
print(combined_tuple) # Outputs: (1, 2, 3, 4, 5, 6)
tuple() Function
The tuple() function converts an iterable into a tuple.
list_to_tuple = tuple([1, 2, 3])
print(list_to_tuple) # Outputs: (1, 2, 3)
Built-In Functions Used on Tuples
Common built-in functions include:
len(): Returns the number of elements in the tuple.
max(), min(): Returns the maximum or minimum value.
print(len(my_tuple)) # Outputs: 3
print(max(my_tuple)) # Outputs: 3
Relation Between Tuples and Lists
Tuples are similar to lists but are immutable. This means once a tuple is created, its
elements cannot be changed.
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
# Tuples are immutable
# my_tuple[0] = 10 # This would raise an error
Relation Between Tuples and Dictionaries
Tuples can be used as keys in dictionaries due to their immutability, while lists cannot.
my_dict_with_tuple_key = {my_tuple: "value"}
print(my_dict_with_tuple_key) # Outputs: {(1, 2, 3): 'value'}
Using zip() Function
The zip() function is used to combine two or more iterables into a tuple of pairs.
keys = ('name', 'age', 'city')
values = ('Alice', 25, 'New York')
zipped = tuple(zip(keys, values))
print(zipped) # Outputs: (('name', 'Alice'), ('age', 25), ('city', 'New York'))
Sets
A set is an unordered collection of unique elements. Sets can be created using curly braces
{} or the set() function.
# Creating a set
my_set = {1, 2, 3, 4, 5}
another_set = set([3, 4, 5, 6, 7])
Set Methods
Common methods for sets include:
add(): Adds an element to the set.
remove(): Removes an element from the set.
union(): Combines two sets.
intersection(): Returns common elements from two sets.
my_set.add(6)
print(my_set) # Outputs: {1, 2, 3, 4, 5, 6}
my_set.remove(2)
print(my_set) # Outputs: {1, 3, 4, 5, 6}
union_set = my_set.union(another_set)
print(union_set) # Outputs: {1, 3, 4, 5, 6, 7}
intersection_set = my_set.intersection(another_set)
print(intersection_set) # Outputs: {3, 4, 5}
Frozen Set
A frozenset is an immutable version of a set. It cannot be modified after creation, making it
hashable and usable as a dictionary key.
# Creating a frozenset
my_frozenset = frozenset([1, 2, 3, 4])
print(my_frozenset) # Outputs: frozenset({1, 2, 3, 4})
Sample Experiments:
13. Write a program to create tuples (name, age, address, college) for at least two
members
concatenate the tuples, and print the concatenated tuples.
14. Write a program to count the number of vowels in a string (No control flow allowed).
15. Write a program to check if a given key exists in a dictionary or not.
16. Write a program to add a new key-value pair to an existing dictionary.
17. Write a program to sum all the items in a given dictionary.
13. Create Tuples and Concatenate
# Program to create tuples and concatenate them
member1 = ("Alice", 25, "123 Main St", "XYZ College")
member2 = ("Bob", 30, "456 Elm St", "ABC University")
# Concatenating the tuples
combined_members = member1 + member2
print("Concatenated Tuples:", combined_members)
output:
Concatenated Tuples: ('Alice', 25, '123 Main St', 'XYZ College', 'Bob', 30, '456 Elm St', 'ABC
University')
14. Count the Number of Vowels in a String (No Control Flow)
# Program to count the number of vowels in a string without using control flow
input_string = "Hello, World!"
vowels = "aeiouAEIOU"
count = sum(map(input_string.count, vowels))
print("Number of vowels:", count)
output:
Number of vowels: 3
15. Check If a Given Key Exists in a Dictionary
# Program to check if a given key exists in a dictionary
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
# Key to check
key_to_check = "age"
# Checking for the key
exists = key_to_check in my_dict
print(f"Key '{key_to_check}' exists in dictionary:", exists)
output:
Key 'age' exists in dictionary: True
16. Add a New Key-Value Pair to an Existing Dictionary
# Program to add a new key-value pair to an existing dictionary
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
# Adding a new key-value pair
my_dict["college"] = "XYZ College"
print("Updated Dictionary:", my_dict)
output:
Updated Dictionary: {'name': 'Alice', 'age': 25, 'city': 'New York', 'college': 'XYZ College'}
17. Sum All the Items in a Given Dictionary
# Program to sum all the items in a given dictionary
my_dict = {"item1": 100, "item2": 200, "item3": 300}
# Summing the values
total_sum = sum(my_dict.values())
print("Sum of all items in the dictionary:", total_sum)
output:
Sum of all items in the dictionary: 600
UNIT– IV
Files: Types of Files, Creating and Reading Text Data, File Methods to Read and Write
Data, Reading and Writing Binary Files, Pickle Module, Reading and Writing CSV Files,
Python OS and [Link] Modules.
Object-Oriented Programming: Classes and Objects, Creating Classes in Python,
Creating Objects in Python, Constructor Method, Classes with Multiple Objects, Class
Attributes Vs Data Attributes, Encapsulation, Inheritance, Polymorphism
Files and Object-Oriented Programming in Python
Files
Types of Files
Python can work with several types of files, primarily:
Text Files: Contains human-readable data (e.g., .txt, .csv).
Binary Files: Contains data in a binary format (e.g., images, audio).
CSV Files: Comma-separated values files used for tabular data.
Creating and Reading Text Data
Text files can be created and read using the open() function. The mode can be specified as
'r' for reading or 'w' for writing.
# Creating and writing to a text file
with open('[Link]', 'w') as file:
[Link]("Hello, World!\n")
[Link]("This is a text file.")
# Reading from a text file
with open('[Link]', 'r') as file:
content = [Link]()
print(content)
output:
Hello, World!
This is a text file
File Methods to Read and Write Data
Common file methods include:
read(): Reads the entire file.
readline(): Reads one line at a time.
readlines(): Reads all lines into a list.
write(): Writes data to the file.
# Example of using readlines
with open('[Link]', 'r') as file:
lines = [Link]()
print(lines)
output:
['Hello, World!\n', 'This is a text file.']
Reading and Writing Binary Files
Binary files can be handled similarly but with 'rb' for reading and 'wb' for writing.
# Writing binary data
data = bytes([120, 3, 255, 0, 100])
with open('[Link]', 'wb') as file:
[Link](data)
# Reading binary data
with open('[Link]', 'rb') as file:
binary_data = [Link]()
print(binary_data)
output:
b'x\x03\xff\x00d'
Pickle Module
The pickle module is used to serialize and deserialize Python objects.
import pickle
# Creating a Python object
data = {'name': 'Alice', 'age': 25}
# Writing to a pickle file
with open('[Link]', 'wb') as file:
[Link](data, file)
# Reading from a pickle file
with open('[Link]', 'rb') as file:
loaded_data = [Link](file)
print(loaded_data)
output:
{'name': 'Alice', 'age': 25}
Reading and Writing CSV Files
The csv module simplifies reading and writing CSV files.
import csv
# Writing to a CSV file
with open('[Link]', 'w', newline='') as file:
writer = [Link](file)
[Link](['Name', 'Age'])
[Link](['Alice', 25])
[Link](['Bob', 30])
# Reading from a CSV file
with open('[Link]', 'r') as file:
reader = [Link](file)
for row in reader:
print(row)
output:
['Name', 'Age']
['Alice', '25']
['Bob', '30']
Python OS and [Link] Modules
The os module provides a way to interact with the operating system, while [Link] helps
manage file paths.
import os
# Check if a file exists
file_exists = [Link]('[Link]')
print("Does the file exist?", file_exists)
# Get the current working directory
current_directory = [Link]()
print("Current Directory:", current_directory)
output:
Does the file exist? True
Object-Oriented Programming (OOP)
Classes and Objects
Classes are blueprints for creating objects. An object is an instance of a class.
Code:
class Dog:
def bark(self):
print("Woof!")
# Creating an object
my_dog = Dog()
my_dog.bark()
output:
Woof!
Creating Classes in Python
Classes are defined using the class keyword.
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
Creating Objects in Python
Objects are created by calling the class.
alice = Person("Alice", 25)
print([Link], [Link]) # Outputs: Alice 25
Constructor Method
The constructor method __init__ initializes object attributes.
class Car:
def __init__(self, model, year):
[Link] = model
[Link] = year
my_car = Car("Toyota", 2020)
print(my_car.model, my_car.year) # Outputs: Toyota 2020
Classes with Multiple Objects
You can create multiple objects from the same class.
bob = Person("Bob", 30)
print([Link], [Link]) # Outputs: Bob 30
Class Attributes vs Data Attributes
Class Attributes: Shared across all instances of the class.
Data Attributes: Unique to each instance.
class Counter:
count = 0 # Class attribute
def __init__(self):
[Link] += 1 # Increment class attribute
counter1 = Counter()
counter2 = Counter()
print([Link]) # Outputs: 2
Encapsulation
Encapsulation restricts access to certain components of an object. It can be achieved using
private attributes.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def get_balance(self):
return self.__balance
account = BankAccount(1000)
print(account.get_balance()) # Outputs: 1000
Inheritance
Inheritance allows a class to inherit attributes and methods from another class.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Woof!")
my_dog = Dog()
my_dog.speak() # Outputs: Animal speaks
Polymorphism
Polymorphism allows methods to do different things based on the object it is acting upon.
class Cat(Animal):
def speak(self):
print("Meow!")
def make_animal_speak(animal):
[Link]()
make_animal_speak(Dog()) # Outputs: Animal speaks
make_animal_speak(Cat()) # Outputs: Meow!
Sample Experiments:
18. Write a program to sort words in a file and put them in another file. The output file
should have only lower-case words, so any upper-case words from source must be
lowered.
19. Python program to print each line of a file in reverse order.
20. Python program to compute the number of characters, words and lines in a file.
21. Write a program to create, display, append, insert and reverse the order of the items
in the array.
22. Write a program to add, transpose and multiply two matrices. Write a Python
program to create a class that represents a shape. Include methods to calculate its area
and perimeter. Implement subclasses for different shapes like circle, triangle, and
square.
18. Sort Words in a File and Save to Another File
# Program to sort words in a file and save to another file in lower-case
with open('[Link]', 'r') as source_file:
words = source_file.read().split() # Read all words
# Convert to lower case and sort
sorted_words = sorted([Link]() for word in words)
# Write sorted words to output file
with open('sorted_output.txt', 'w') as output_file:
for word in sorted_words:
output_file.write(word + '\n')
19. Print Each Line of a File in Reverse Order
# Program to print each line of a file in reverse order
with open('[Link]', 'r') as file:
for line in file:
print([Link]()[::-1]) # Reverse the line and print
20. Compute Number of Characters, Words, and Lines in a File
# Program to compute the number of characters, words, and lines in a file
with open('[Link]', 'r') as file:
content = [Link]()
num_lines = [Link]('\n') + 1 # Lines
num_words = len([Link]()) # Words
num_characters = len(content) # Characters
print(f"Lines: {num_lines}, Words: {num_words}, Characters: {num_characters}")
21. Array Operations: Create, Display, Append, Insert, Reverse
# Program to create, display, append, insert, and reverse an array
array = [1, 2, 3, 4, 5]
# Display the array
print("Original Array:", array)
# Append an item
[Link](6)
print("After Appending:", array)
# Insert an item at a specific index
[Link](2, 10) # Insert 10 at index 2
print("After Insertion:", array)
# Reverse the array
[Link]()
print("Reversed Array:", array)
22. Matrix Operations and Shape Class
# Program to add, transpose, and multiply two matrices
def add_matrices(A, B):
return [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))]
def transpose_matrix(A):
return [[A[j][i] for j in range(len(A))] for i in range(len(A[0]))]
def multiply_matrices(A, B):
return [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(len(B[0]))] for i in
range(len(A))]
# Example matrices
matrix1 = [[1, 2, 3], [4, 5, 6]]
matrix2 = [[7, 8, 9], [10, 11, 12]]
# Performing operations
added_matrix = add_matrices(matrix1, matrix2)
transposed_matrix = transpose_matrix(matrix1)
multiplied_matrix = multiply_matrices(matrix1, transpose_matrix(matrix2))
print("Added Matrix:", added_matrix)
print("Transposed Matrix:", transposed_matrix)
print("Multiplied Matrix:", multiplied_matrix)
# Shape Class
class Shape:
def area(self):
pass
def perimeter(self):
pass
class Circle(Shape):
def __init__(self, radius):
[Link] = radius
def area(self):
return 3.14 * [Link] ** 2
def perimeter(self):
return 2 * 3.14 * [Link]
class Square(Shape):
def __init__(self, side):
[Link] = side
def area(self):
return [Link] ** 2
def perimeter(self):
return 4 * [Link]
class Triangle(Shape):
def __init__(self, base, height):
[Link] = base
[Link] = height
def area(self):
return 0.5 * [Link] * [Link]
def perimeter(self, side1, side2):
return [Link] + side1 + side2
# Example usage
circle = Circle(5)
square = Square(4)
triangle = Triangle(3, 6)
print("Circle Area:", [Link](), "Perimeter:", [Link]())
print("Square Area:", [Link](), "Perimeter:", [Link]())
print("Triangle Area:", [Link]())
UNIT– V
Introduction to Data Science: Functional Programming, JSON and XML in Python,
NumPy with Python, Pandas.
Introduction to Data Science
Functional Programming
Functional programming is a programming paradigm that treats computation as the
evaluation of mathematical functions and avoids changing state or mutable data. In
Python, functional programming features include:
Key Concepts
First-Class Functions: Functions in Python can be passed as arguments,
returned from other functions, and assigned to variables.
Higher-Order Functions: Functions that take other functions as arguments or
return them.
Lambda Functions: Anonymous functions defined with the lambda keyword.
Example
# Higher-order function example
def apply_function(func, value):
return func(value)
# Using a lambda function
result = apply_function(lambda x: x ** 2, 5)
print(result) # Outputs: 25
JSON and XML in Python
JSON (JavaScript Object Notation)
JSON is a lightweight data interchange format that is easy for humans to read and write.
Python's json module allows for parsing and manipulating JSON data.
Example
import json
# Creating a JSON object
data = {'name': 'Alice', 'age': 25, 'city': 'New York'}
json_data = [Link](data) # Convert to JSON string
print(json_data)
# Parsing JSON
parsed_data = [Link](json_data)
print(parsed_data['name']) # Outputs: Alice
XML (eXtensible Markup Language)
XML is a markup language that defines rules for encoding documents. Python's xml
library provides tools to work with XML data.
Example
import [Link] as ET
# Creating an XML structure
data = [Link]('person')
name = [Link](data, 'name')
[Link] = 'Alice'
age = [Link](data, 'age')
[Link] = '25'
# Convert to string
xml_data = [Link](data, encoding='unicode')
print(xml_data)
# Parsing XML
root = [Link](xml_data)
print([Link]('name').text) # Outputs: Alice
NumPy with Python
NumPy is a powerful library for numerical computing in Python. It provides support for
arrays, matrices, and a wide range of mathematical functions.
Key Features
N-dimensional arrays: Efficient storage and operations on large datasets.
Mathematical Functions: Element-wise operations on arrays.
Example
import numpy as np
# Creating a NumPy array
arr = [Link]([1, 2, 3, 4, 5])
# Performing operations
squared = arr ** 2
print(squared) # Outputs: [ 1 4 9 16 25]
# Matrix operations
matrix_a = [Link]([[1, 2], [3, 4]])
matrix_b = [Link]([[5, 6], [7, 8]])
matrix_product = [Link](matrix_a, matrix_b)
print(matrix_product)
Pandas
Pandas is a powerful library for data manipulation and analysis. It provides data
structures like Series and DataFrame for handling structured data.
Key Features
DataFrame: A two-dimensional labeled data structure, similar to a table in a
database or a spreadsheet.
Data Manipulation: Functions for filtering, grouping, and transforming data.
Example
import pandas as pd
# Creating a DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = [Link](data)
# Displaying the DataFrame
print(df)
# Filtering data
filtered_df = df[df['Age'] > 28]
print(filtered_df)
Sample Experiments:
23. Python program to check whether a JSON string contains complex object or not.
24. Python Program to demonstrate NumPy arrays creation using array () function.
25. Python program to demonstrate use of ndim, shape, size, dtype.
26. Python program to demonstrate basic slicing, integer and Boolean indexing.
27. Python program to find min, max, sum, cumulative sum of array
28. Create a dictionary with at least five keys and each key represent value as a list
where this list contains at least ten values and convert this dictionary as a pandas data
frame and explore the data through the data frame as follows:
a) Apply head () function to the pandas data frame
b) Perform various data selection operations on Data Frame
29. Select any two columns from the above data frame, and observe the change in one
attribute with respect to other attribute with scatter and plot operations in matplotlib
23. Check Whether a JSON String Contains a Complex Object
import json
# Sample JSON string
json_string = '{"name": "Alice", "age": 25, "address": {"city": "New York", "zip": "10001"}}'
# Function to check for complex objects
def contains_complex_object(json_str):
try:
data = [Link](json_str)
return any(isinstance(value, dict) for value in [Link]())
except [Link]:
return False
# Check and print result
has_complex = contains_complex_object(json_string)
print("Contains complex object:", has_complex)
output:
Contains complex object: True
24. Demonstrate NumPy Arrays Creation Using array() Function
import numpy as np
# Creating a NumPy array using array() function
array1 = [Link]([1, 2, 3, 4, 5])
array2 = [Link]([[1, 2, 3], [4, 5, 6]])
print("1D Array:\n", array1)
print("2D Array:\n", array2)
output:
1D Array:
[1 2 3 4 5]
2D Array:
[[1 2 3]
[4 5 6]]
25. Demonstrate Use of ndim, shape, size, and dtype
import numpy as np
# Create a NumPy array
array = [Link]([[1, 2, 3], [4, 5, 6]])
# Demonstrating properties
print("Number of Dimensions (ndim):", [Link])
print("Shape of the array (shape):", [Link])
print("Total Number of Elements (size):", [Link])
print("Data Type of the Array (dtype):", [Link])
output:
Number of Dimensions (ndim): 2
Shape of the array (shape): (2, 3)
Total Number of Elements (size): 6
Data Type of the Array (dtype): int64
26. Basic Slicing, Integer and Boolean Indexing
import numpy as np
# Create a NumPy array
array = [Link]([10, 20, 30, 40, 50])
# Basic slicing
sliced_array = array[1:4] # Slicing from index 1 to 3
print("Sliced Array:", sliced_array)
# Integer indexing
indices = [0, 2, 4]
indexed_array = array[indices]
print("Indexed Array:", indexed_array)
# Boolean indexing
boolean_index = array > 25
filtered_array = array[boolean_index]
print("Filtered Array (elements > 25):", filtered_array)
ouput:
Sliced Array: [20 30 40]
Indexed Array: [10 30 50]
Filtered Array (elements > 25): [30 40 50]
27. Find Min, Max, Sum, Cumulative Sum of Array
import numpy as np
# Create a NumPy array
array = [Link]([1, 2, 3, 4, 5])
# Min, Max, Sum, Cumulative Sum
minimum = [Link](array)
maximum = [Link](array)
total_sum = [Link](array)
cumulative_sum = [Link](array)
print("Minimum:", minimum)
print("Maximum:", maximum)
print("Sum:", total_sum)
print("Cumulative Sum:", cumulative_sum)
output:
Minimum: 1
Maximum: 5
Sum: 15
Cumulative Sum: [ 1 3 6 10 15]
28. Create a Dictionary and Convert to Pandas DataFrame
import pandas as pd
# Creating a dictionary with keys as lists
data_dict = {
'A': list(range(10)),
'B': list(range(10, 20)),
'C': list(range(20, 30)),
'D': list(range(30, 40)),
'E': list(range(40, 50))
}
# Converting the dictionary to a DataFrame
df = [Link](data_dict)
# a) Apply head() function
print("DataFrame Head:\n", [Link]())
# b) Perform various data selection operations
# Selecting a specific column
print("Column A:\n", df['A'])
# Selecting multiple columns
print("Columns A and B:\n", df[['A', 'B']])
# Selecting rows based on condition
print("Rows where A > 5:\n", df[df['A'] > 5])
output:
DataFrame Head:
A B C D E
0 0 10 20 30 40
1 1 11 21 31 41
2 2 12 22 32 42
3 3 13 23 33 43
4 4 14 24 34 44
Column A:
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
Name: A, dtype: int64
Columns A and B:
A B
0 0 10
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
6 6 16
7 7 17
8 8 18
9 9 19
Rows where A > 5:
A B C D E
6 6 16 26 36 46
7 7 17 27 37 47
8 8 18 28 38 48
9 9 19 29 39 49
29. Scatter Plot to Observe Change in Attributes
import [Link] as plt
# Selecting two columns from the DataFrame
x = df['A']
y = df['B']
# Creating a scatter plot
[Link](x, y)
[Link]("Scatter Plot of B vs A")
[Link]("A")
[Link]("B")
[Link]()
# Creating a line plot for the same data
[Link](x, y, marker='o')
[Link]("Line Plot of B vs A")
[Link]("A")
[Link]("B")
[Link]()