0% found this document useful (0 votes)
6 views58 pages

Python Programming Lab Manual II-i

The Python Programming Lab Manual covers the history, installation, and fundamentals of Python, including control flow, data types, and operators. It also outlines various applications of Python in web development, data science, and more, along with sample experiments and programming tasks. Additionally, it provides insights into functions, variable scope, and string operations.

Uploaded by

chilakaiah45
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views58 pages

Python Programming Lab Manual II-i

The Python Programming Lab Manual covers the history, installation, and fundamentals of Python, including control flow, data types, and operators. It also outlines various applications of Python in web development, data science, and more, along with sample experiments and programming tasks. Additionally, it provides insights into functions, variable scope, and string operations.

Uploaded by

chilakaiah45
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DEPARTMENT OF DATA SCIENCE

II [Link] I SEM

PYTHON PROGRAMMING LAB MANUAL


Expt. No. : Page No. :
Date :

UNIT-1
1. History of Python
2. Thrust Areas
3. Installation
4. Python Fundamentals
5. Control Flow

1. History of Python
Python was created by Guido van Rossum and first released in 1991. Named after Monty Python’s Flying
Circus, it emphasizes: - Code readability - Simplicity in design - Ease of learning - Extensive community
support

2. Thrust Areas
Python excels in multiple domains:

Web Development
• Django and Flask frameworks
• Web application development
• RESTful API creation

Data Science
• NumPy for numerical computing
• Pandas for data analysis
• Scikit-Learn for machine learning

Additional Areas
• Automation and scripting
• Game development with Pygame
• Network programming
• IoT applications
• General-purpose programming

3. Installation
Anaconda Distribution
 Download from [Link]
 Run installer
 Verify with: conda --version

Jupyter Notebook
• Included with Anaconda
• Start with: jupyter notebook
• Supports interactive coding and documentation

4. Python Fundamentals
Identifiers and Keywords

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

1
Expt. No. : Page No. :
Date :

• Identifiers: Names for variables, functions, classes


– Must start with letter/underscore
– Case sensitive
– Cannot use reserved keywords
• Keywords: Reserved words like if, else, while, for

Variables and Data Types


Basic Types: - int: Integer numbers - float: Decimal numbers - str: Text strings - bool: True/False values -
list: Ordered collections - tuple: Immutable sequences - dict: Key-value pairs - set: Unique unordered
elements

Operators
Arithmetic Operators
– + (addition)
– - (subtraction)
– * (multiplication)
– / (division)
– ** (exponentiation)
– // (floor division)
– % (modulus)
Comparison Operators
– == (equal to)
– != (not equal to)
– >, < (greater/less than)
– >=, <= (greater/less than or equal)
Logical Operators
– and
– or
– not

Input/Output
# Input
name =input("Enter your name: ")

# Output
print(f"Hello, {name}!")

Type Conversions
• Explicit: Using functions
str_num ="123"
num =int(str_num) # Convert to integer
• Implicit: Automatic conversion

x =5+2.0# Result is float (7.0)

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

2
Expt. No. : Page No. :
Date :

5. Control Flow
Conditional Statements
if condition:
# code block
elif another_condition:
# code block
else:
# code block

Loops
While Loop
while condition:
# repeated code

For Loop
for item in sequence:
# code for each item

Exception Handling
try:
# Code that might raise error
except ExceptionType:
# Handle the error
else:
# Run if no error
finally:
# Always runs

Best Practices
 Use clear, descriptive names
 Follow PEP 8 style guide
 Comment your code appropriately
 Keep functions and classes focused
 Use proper indentation (4 spaces)

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

3
Expt. No. : Page No. :
Date :

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) Bit wise 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 multiplication table of a given number.

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

4
Expt. No. : Page No. :
Date :

1. Write a program to find the largest element among three Numbers.

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number is", largest)

OUTPUT

Enter first number: 5

Enter second number: 7


Enter third number: 10

The largest number is 10.0

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

5
Expt. No. : Page No. :
Date :

2. Write a Program to display all prime numbers within an interval

lower_value = int(input ("Please, Enter the Lowest Range Value: "))


upper_value = int(input ("Please, Enter the Upper Range Value: "))

print ("The Prime Numbers in the range are: ")


for number in range (lower_value, upper_value + 1):
if number > 1:
for i in range (2, number):
if (number % i) == 0:
break
else:
print (number)

OUTPUT

Please, Enter the Lowest Range Value: 35


Please, Enter the Upper Range Value: 50
The Prime Numbers in the range are:
37
41
43
47

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

6
Expt. No. : Page No. :
Date :

3. Write a program to swap two numbers without using a temporary variable.

x = 10
y=5
# Code to swap 'x' and 'y'
# x now becomes 15
x=x+y
# y becomes 10
y=x-y
# x becomes 5
x=x-y
print("After Swapping:x =", x, " y =", y)

OUTPUT
After Swapping : x=5 y=10

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

7
Expt. No. : Page No. :
Date :

4. Demonstrate the following Operators in Python with suitable examples.

i) Arithmetic Operators ii) Relational Operators iii) Assignment Operators iv) Logical
Operators v) Bit wise Operators vi) Ternary Operator vii) Membership Operators viii)
Identity Operators
(i) Arithmetic Operators

These operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc.
PROGRAM
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)

OUTPUT
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333335
Floor Division: 3
Modulus: 1
Exponentiation: 1000

ii) Relational Operators


PROGRAM
a = 10
b = 20

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

8
Expt. No. : Page No. :
Date :

print("a == b:", a == b)

print("a != b:", a != b)
print("a > b:", a > b)
print("a < b:", a < b)
print("a >= b:", a >= b)
print("a <= b:", a <= b)

OUTPUT
a == b: False
a != b: True
a > b: False
a < b: True
a >= b: False
a <= b: True

iii) Assignment Operators


PROGRAM
a=5
print("a =", a)
a += 2
print("a += 2:", a)

a -= 1

print("a -= 1:", a)
a *= 3
print("a *= 3:", a)
a /= 2
print("a /= 2:", a)

a //= 2

print("a //= 2:", a)


a %= 3
print("a %= 3:", a)

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

9
Expt. No. : Page No. :
Date :

a **= 2

print("a **= 2:", a)

OUTPUT
a=5
a += 2: 7
a -= 1: 6
a *= 3: 18

a /= 2: 9.0
a //= 2: 4.0
a %= 3: 1.0
a **= 2: 1.0

iv)Logical Operators
PROGRAM

x = True
y = False
print("x and y:", x and y)
print("x or y:", x or y)
print("not x:", not x)
OUTPUT
x and y: False
x or y: True
not x: False

v) Bitwise Operators

PROGRAM
a = 10 # 1010 in binary

b = 4 # 0100 in binary
print("a & b:", a & b)

print("a | b:", a | b)
print("a ^ b:", a ^ b)

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

10
Expt. No. : Page No. :
Date :

print("~a:", ~a)

print("a << 2:", a << 2)


print("a >> 2:", a >> 2)
OUTPUT
a & b: 0
a | b: 14
a ^ b: 14

~a: -11
a << 2: 40
a >> 2: 2

vi) Ternary Operator

PROGRAM
a = 10
b = 20
max_value = a if a > b else b
print("Maximum value is:", max_value)

OUTPUT

Maximum value is: 20

vii)Membership Operators

PROGRAM
my_list = [1, 2, 3, 4, 5]
print("3 in my_list:", 3 in my_list) # in
print("6 not in my_list:", 6 not in my_list) # not in

OUTPUT
3 in my_list: True

6 not in my_list: True

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

11
Expt. No. : Page No. :
Date :

viii) Identity Operators

PROGRAM
a = 10
b = 10

c = [1, 2, 3]
d = [1, 2, 3]
print("a is b:", a is b) # is

print("a is not b:", a is not b) # is not


print("c is d:", c is d) # is
print("c is not d:", c is not d) # is not

OUTPUT
a is b: True
a is not b: False

c is d: False
c is not d: True

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

12
Expt. No. : Page No. :
Date :

5. Write a program to add and multiply complex numbers

def addComplex( z1, z2):


return z1+z2
def subComplex( z1, z2):
return z1-z2
def mulComplex( z1, z2):
return z1*z2
# driver program
z1 = complex(2, 3)
z2 = complex(1, 2)
print( "Addition is : ", addComplex(z1, z2))
print( "Subtraction is : ", subComplex(z1, z2))
print( "Multiplication is : ", mulComplex(z1, z2))

OUTPUT

Addition is : (3+5j)
Subtraction is : (1+1j)
Multiplication is : (-4+7j)

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

13
Expt. No. : Page No. :
Date :

6. Write a program to print multiplication table of a given number.


number = int(input("Enter the number :"))

print("Multiplication table of:" , num )


for i in range(1, 11):
print("num, "x",I, "=", num *i )

OUTPUT
Enter the number: 4

Multiplication table of 4:
4x1=4
4x2=8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20

4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

14
Expt. No. : Page No. :
Date :

UNIT-2
1. Functions
Built-In Functions
Python provides numerous built-in functions that are always available: - print(): Output text/values - len():
Return length of object - type(): Return type of object - int(), float(), str(): Type conversion functions -
min(), max(): Find minimum/maximum values - sum(): Calculate sum of iterable

Function Definition and Calling


Functions are defined using the def keyword:
def greet(name):
"""Docstring: Explains function purpose"""
print(f"Hello, {name}!")

# Calling the function


greet("Alice") # Output: Hello, Alice!

Return Statement vs Void Functions


• Functions with return statement:
def add(a, b):
return a + b # Returns value
result = add(5, 3) # result = 8
• Void functions (no return value):
def display_info(name):
print(f"Info: {name}") # No return statement

Variable Scope and Lifetime


• Local Variables: Exist only within function
• Global Variables: Accessible throughout program
• Nonlocal Variables: Used in nested functions
global_var = 10 # Global variable

def function():
local_var = 20 # Local variable
print(global_var) # Can access global
print(local_var) # Can access local

Function Parameters
Default Parameters:
def greet(name="User"):
print(f"Hello, {name}!")
greet() # Uses default value
greet("Alice") # Uses provided value
Keyword Arguments:

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

15
Expt. No. : Page No. :
Date :

def student_info(name, age, course):


print(f"{name} is {age} years old, studying {course}")

student_info(age=20, name="John", course="Python") # Order doesn't matter

*args and **kwargs:


• *args: Variable number of positional arguments
• **kwargs: Variable number of keyword arguments
def example(*args, **kwargs):
print("Args:", args) # Tuple of arguments
print("Kwargs:", kwargs) # Dictionary of keyword arguments

example(1, 2, name="John", age=25)

2. Strings
Creating and Storing Strings
str1 = "Hello" # Using double quotes
str2 = 'World' # Using single quotes
str3 = """Multiline
string""" # Using triple quotes

String Operations
• Concatenation: "Hello" + "World"
• Repetition: "Ha" * 3 # “HaHaHa”
• Length: len("Hello") # 5

String Indexing and Slicing


text = "Python"
print(text[0]) # 'P'
print(text[-1]) # 'n'
print(text[0:2]) # 'Py'
print(text[::2]) # 'Pto'

Common String Methods


• upper(), lower(): Change case
• strip(): Remove whitespace
• split(): Split string into list
• join(): Join items with string
• replace(): Replace substring
• find(), index(): Find substring position

String Formatting
%-formatting:
"Hello, %s" % "World"

[Link]():
"Hello, {}".format("World")
f-strings (Python 3.6+):

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

16
Expt. No. : Page No. :
Date :

name = "World"
f"Hello, {name}"

3. Lists

Creating and Basic Operations


# Creating lists
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

# Basic operations
length = len(numbers) # Length
concat = [1, 2] + [3, 4] # Concatenation
repeat = [0] * 3 # Repetition

List Indexing and Slicing


numbers = [1, 2, 3, 4, 5]
print(numbers[0]) # First element
print(numbers[-1]) # Last element
print(numbers[1:3]) # Slice: [2, 3]
print(numbers[::2]) # Every second element

Built-in Functions for Lists


• len(): Length of list
• sum(): Sum of numeric list
• max(), min(): Maximum/minimum values
• sorted(): Return sorted list
• list(): Convert to list

List Methods
• append(): Add element to end
• extend(): Add multiple elements
• insert(): Insert at specific position
• remove(): Remove specific value
• pop(): Remove and return element
• sort(): Sort list in-place
• reverse(): Reverse list in-place

The del Statement


numbers = [1, 2, 3, 4, 5]
del numbers[0] # Delete single element
del numbers[1:3] # Delete slice
del numbers # Delete entire list

Important Theory Concepts


Function Design Principles:
– Single Responsibility Principle
– Don’t Repeat Yourself (DRY)
– Clear and descriptive naming

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

17
Expt. No. : Page No. :
Date :

– Appropriate documentation
String Implementation:
– Strings are immutable in Python
– Memory efficient due to string interning
– Unicode support by default in Python 3
List Implementation:
– Dynamic array implementation
– Over-allocation for efficiency
– Reference counting for memory management
Variable Scope Rules:
– LEGB Rule: Local, Enclosing, Global, Built-in
– Name resolution follows this hierarchy
– Variable shadowing considerations
Memory Management:
– Function parameters passed by reference
– Mutable vs immutable objects behavior
– Garbage collection handling

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

18
Expt. No. : Page No. :
Date :

Sample Experiments:
1. Write a program to define a function with multiple return values.
2. Write a program to define a function using default arguments.
3. Write a program to find the length of the string without using any library functions.
4. Write a program to check if the substring is present in a given string or not.
5. Write a program to perform the given operations on a list: i. Addition ii. Insertion iii. slicing
6. Write a program to perform any 5 built-in functions by taking any list.

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

19
Expt. No. : Page No. :
Date :

1. Write a program to define a function with multiple return values.

# Function that returns multiple values

def name():
return "John","Armin"

# print the tuple with the returned values


print(name())

# get the individual items


name_1, name_2 = name()
print(name_1, name_2)

OUTPUT

('John', 'Armin')
John Armin

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

20
Expt. No. : Page No. :
Date :

2. Write a program to define a function using default arguments.

Program_1

def greet (name, subject, dept="CSE"):


print(f"Hi {name}")
print(f"Do you teach {subject} ?")
print(f"Are you from {dept} department ?")
greet("John", "Python")

OUTPUT

Hi John
Do you teach Python ?
Are you from CSE department ?

Program_2
# Function definition
def showinfo( name, city = "Hyderabad" ):
print ("Name:", name)
print ("City:", city)
return
showinfo(name = "Ansh", city = "Delhi")
showinfo(name = "Shrey")

OUTPUT

Name: Ansh
City: Delhi
Name: Shrey
City: Hyderabad

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

21
Expt. No. : Page No. :
Date :

[Link] a program to find the length of the string without using any library functions.

string = input("Enter the String:")


count=0
for i in string:
count=count+1
print("Length of the given string is:",
count)

OUTPUT

Enter the String:Hello world


Length of the given string is: 11

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

22
Expt. No. : Page No. :
Date :

4. Write a program to check if the substring is present in a given string or not

string = input("Enter the String:")


substring = input("Enter substring to check in string:")
if substring in string:
print("yes substring is present")
else:
print("substring is absent")

OUTPUT

Enter the String:Hello world


Enter substring to check in
string:world
yes substring is present

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

23
Expt. No. : Page No. :
Date :

[Link] a program to perform the given operations on a list:


i. Addition
ii. Insertion
iii. slicing

my_list = [10, 20, 30, 40, 50]


# i. Addition
# Adding an element to the end of the list using the append method
my_list.append(60)
print("After addition:", my_list)

# ii. Insertion
# Inserting an element at a specific position in the list
# Example: Insert 25 at index 2 (third position)
my_list.insert(2, 25)
print("After insertion:", my_list)

# iii. Slicing
# Slicing the list to get a sublist
# Example: Get a slice from index 1 to 4 (excluding index 4)
sliced_list = my_list[1:4]
print("Sliced list (index 1 to 3):", sliced_list)

OUTPUT

After addition: [10, 20, 30, 40, 50, 60]


After insertion: [10, 20, 25, 30, 40, 50, 60]
Sliced list (index 1 to 3): [20, 25, 30]

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

24
Expt. No. : Page No. :
Date :

6. Write a program to perform any 5 built-in functions by taking any list

# Initial list of integers


numbers = [25, 10, 75, 30, 50, 20]
# 1. Length of the list
length_of_list = len(numbers)
print("Length of the list:", length_of_list)
# 2. Maximum value in the list
max_value = max(numbers)
print("Maximum value in the list:", max_value)
# 3. Minimum value in the list
min_value = min(numbers)
print("Minimum value in the list:", min_value)
# 4. Sorting the list in ascending order
sorted_list = sorted(numbers)
print("List after sorting:", sorted_list)
# 5. Reversing the list
[Link]()
print("List after reversing:", numbers)

OUTPUT

Length of the list: 6


Maximum value in the list: 75
Minimum value in the list: 10
List after sorting: [10, 20, 25, 30, 50, 75]
List after reversing: [20, 50, 30, 75, 10, 25]

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

25
Expt. No. : Page No. :
Date :

UNIT-3
1. Dictionaries

Introduction
Dictionaries are unordered collections of key-value pairs. They are mutable and dynamic, allowing you to
store and retrieve values using unique keys.
Creating Dictionaries
# Empty dictionary
empty_dict = {}
empty_dict2 = dict()

# Dictionary with items


student = {
"name": "John",
"age": 20,
"grade": "A"
}

Accessing and Modifying Key:Value Pairs


# Accessing values
print(student["name"]) # Output: John

# Modifying values
student["age"] = 21
student["subject"] = "Python" # Adding new key-value pair

Built-in Dictionary Functions


• len(): Returns number of key-value pairs
• type(): Returns type of dictionary
• str(): Returns string representation
• dict(): Creates dictionary from sequence of key-value pairs

Dictionary Methods
# Common methods
[Link]() # Returns list of keys
[Link]() # Returns list of values
[Link]() # Returns list of key-value pairs
[Link]("name") # Safe way to access values
[Link]({"city": "New York"}) # Update multiple values
[Link]("age") # Remove specific key-value pair

The del Statement


del student["grade"] # Remove specific key-value pair
del student # Delete entire dictionary

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

26
Expt. No. : Page No. :
Date :

2. Tuples

Introduction
Tuples are ordered, immutable sequences of elements. They are similar to lists but cannot be modified after
creation.

Creating Tuples
# Empty tuple
empty_tuple = ()
empty_tuple2 = tuple()

# Tuple with items


coordinates = (10, 20)
single_item = (1,) # Note the comma

Basic Tuple Operations


# Concatenation
tuple1 = (1, 2)
tuple2 = (3, 4)
result = tuple1 + tuple2 # (1, 2, 3, 4)

# Repetition
repeated = tuple1 * 2 # (1, 2, 1, 2)

Indexing and Slicing


numbers = (0, 1, 2, 3, 4, 5)
print(numbers[0]) # First element
print(numbers[-1]) # Last element
print(numbers[1:4]) # Slice from index 1 to 3

Built-in Tuple Functions


• len(): Returns length of tuple
• max(): Returns maximum value
• min(): Returns minimum value
• sum(): Returns sum of numeric tuple
• tuple(): Converts sequence to tuple

Relation with Lists and Dictionaries


# List to Tuple
my_list = [1, 2, 3]
my_tuple = tuple(my_list)

# Dictionary to Tuple
my_dict = {"a": 1, "b": 2}
key_tuple = tuple(my_dict.keys())

Using zip() Function


names = ("John", "Jane")
ages = (25, 30)

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

27
Expt. No. : Page No. :
Date :

zipped = zip(names, ages) # Creates iterator of tuples

3. Sets
Introduction
Sets are unordered collections of unique elements. They eliminate duplicates automatically and support
mathematical set operations.

Creating Sets
# Empty set
empty_set = set() # Note: {} creates empty dictionary

# Set with items


fruits = {"apple", "banana", "orange"}

Set Methods
# Adding elements
[Link]("mango")
[Link](["grape", "kiwi"])

# Removing elements
[Link]("apple") # Raises error if not found
[Link]("apple") # No error if not found
[Link]() # Removes random element
[Link]() # Removes all elements

# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print([Link](set2)) # {1, 2, 3, 4, 5}
print([Link](set2)) # {3}
print([Link](set2)) # {1, 2}

Frozenset
Frozenset is an immutable version of a set.
frozen = frozenset([1, 2, 3])
# [Link](4) # This would raise an error
Key Points to Remember:
 Dictionaries use key-value pairs and are mutable
 Tuples are immutable and ordered
 Sets contain unique elements and are unordered
 Frozensets are immutable sets
 Each collection type has its specific use cases based on:
o Mutability requirements
o Order requirements
o Uniqueness requirements
o Access pattern requirements

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

28
Expt. No. : Page No. :
Date :

Sample Experiments:
1. Write a program to create tuples (name, age, address, college) for at least two members and concatenate
the tuples and print the concatenated tuples.
2. Write a program to count the number of vowels in a string (No control flow allowed).
3. Write a program to check if a given key exists in a dictionary or not.
4. Write a program to add a new key-value pair to an existing dictionary.
5. Write a program to sum all the items in a given dictionary.

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

29
Expt. No. : Page No. :
Date :

1. Write a program to create tuples (name, age, address, college) for at least two members and
concatenate the tuples and print the concatenated tuples.

tuple1 = ('Ram', 20, 'Andhra pradesh', 'JNTUK university' )


tuple2 = ('john', 22, 'Canada', 'Alberta university')
tuple3 = tuple1+tuple2
print(tuple3)

Output:
('Ram', 20, 'Andhra pradesh', 'JNTUK university', 'john', 22, 'Canada', 'Alberta university')

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

30
Expt. No. : Page No. :
Date :

2. Write a program to count the number of vowels in a string (No control flow allowed).

# Input string
input_string = "Hello World"

# Define a set of vowels


vowels = "aeiouAEIOU"

# Count the vowels using sum() and a generator expression


vowel_count = sum(map(input_string.lower().count, "aeiou"))

# Print the result


print("Number of vowels:", vowel_count

Output:
Number of vowels: 3

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

31
Expt. No. : Page No. :
Date :

3. Write a program to check if a given key exists in a dictionary or not.

# Sample dictionary
my_dict = {"name": "Alice", "age": 25, "address": "123 Main St"}

# Key to check
key_to_check = "college"

# Check if the key exists in the dictionary


if key_to_check in my_dict:
print(f"The key '{key_to_check}' exists in the dictionary.")
else:
print(f"The key '{key_to_check}' does not exist in the dictionary.")

Output:

The key 'college' does not exist in the dictionary.

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

32
Expt. No. : Page No. :
Date :

4. Write a program to add a new key-value pair to an existing dictionary.

# Existing dictionary

my_dict = {"name": "Ram", "age": 25, "address": "Kakinada"}

# New key-value pair

new_key = "college"

new_value = "JNTUK"

# Add the new key-value pair to the dictionary

my_dict[new_key] = new_value

# Print the updated dictionary

print("Updated dictionary:", my_dict)

OUTPUT:
Updated dictionary: {'name': 'Ram', 'age': 25, 'address': 'Kakinada', 'college': 'JNTUK'}

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

33
Expt. No. : Page No. :
Date :

5. Write a program to sum all the items in a given dictionary.

# Given dictionary
my_dict = {"item1": 10, "item2": 20, "item3": 30, "item4": 40}
# Sum all the values in the dictionary
total_sum = sum(my_dict.values())
# Print the result
print("Sum of all items:", total_sum)

Output:
Sum of all items: 100

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

34
Expt. No. : Page No. :
Date :

UNIT-4
1. File Handling

Types of Files
Text Files: These files contain human-readable data stored as characters. Each character is represented by
a specific numeric code (e.g., ASCII or Unicode). Text files are the most common type of file used for
storing and exchanging data.
Binary Files: These files contain raw, machine-readable data stored as bytes (sequences of 0s and 1s).
Binary files can represent various types of data, such as images, audio, video, and executable programs.
Binary files are not directly human-readable and require specialized software or libraries to interpret the
data.

File Operations
The basic file operations in Python include: - Opening a file: Using the open() function, which returns a
file object that represents the opened file. - Reading from a file: Using methods like read(), readline(), and
readlines() to retrieve data from the file. - Writing to a file: Using the write() and writelines() methods to
add data to the file. - Closing a file: Using the close() method to ensure the file is properly closed and its
resources are released.
The with statement is commonly used to handle file operations, as it automatically takes care of closing the
file when the block of code is finished executing.

Text File Operations


For text files, you can use the "r" (read), "w" (write), and "a" (append) modes when opening a file. The
default mode is "r" if no mode is specified.
# Writing to a text file
with open("[Link]", "w") as file:
[Link]("Hello, World!")

# Reading from a text file


with open("[Link]", "r") as file:
content = [Link]()
print(content)
Binary File Operations
For binary files, you need to use the "rb" (read binary) and "wb" (write binary) modes when opening a file.
# Writing to a binary file
with open("[Link]", "wb") as file:
[Link](b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR...")

# Reading from a binary file


with open("[Link]", "rb") as file:
content = [Link]()

Pickle Module

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

35
Expt. No. : Page No. :
Date :

The Pickle module is used to serialize and deserialize Python objects. Serialization is the process of
converting an object into a stream of bytes, which can be stored or transmitted and then reconstructed later.
Deserialization is the reverse process of reconstructing the original object from the stored or transmitted
data.
import pickle

# Serializing an object
data = {"name": "John", "age": 30}
with open("[Link]", "wb") as file:
[Link](data, file)

# Deserializing an object
with open("[Link]", "rb") as file:
loaded_data = [Link](file)
print(loaded_data)

CSV Files
CSV (Comma-Separated Values) files are a common format for storing and exchanging tabular data. The
csv module in Python provides a convenient way to read and write CSV files.
import csv

# Writing to a CSV file


data = [["Name", "Age"], ["John", 30], ["Jane", 25]]
with open("[Link]", "w", newline="") as file:
writer = [Link](file)
[Link](data)

# Reading from a CSV file


with open("[Link]", "r") as file:
reader = [Link](file)
for row in reader:
print(row)

OS and [Link] Modules


The os and [Link] modules in Python provide a way to interact with the operating system, allowing you to
perform various file and directory-related operations.
import os

# Get the current working directory


current_dir = [Link]()
print(current_dir)

# Create a new directory


[Link]("new_folder")

# Check if a file or directory exists

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

36
Expt. No. : Page No. :
Date :

if [Link]("[Link]"):
print("File exists")
else:
print("File does not exist")

2. Object-Oriented Programming (OOP)

Classes and Objects


In object-oriented programming, a class is a user-defined data type that defines the properties (attributes)
and behaviors (methods) of an object. An object is an instance of a class, which means it has its own set of
attributes and can perform the methods defined in the class.

Creating Classes in Python


To create a class in Python, you use the class keyword followed by the name of the class. Inside the class,
you can define attributes and methods.
class Dog:
def init (self, name, breed):
[Link] = name
[Link] = breed

def bark(self):
print("Woof!")

Constructor Method (init)


The init method is a special method in Python that is used to initialize the object’s attributes when an
object is created. It is automatically called when you create a new object from the class.

Classes with Multiple Objects


Each object created from a class has its own set of attributes and can perform its own methods. This allows
you to create multiple instances of a class, each with its own unique data.
dog1 = Dog("Buddy", "Labrador")
dog2 = Dog("Bella", "Poodle")

print([Link]) # Output: Buddy


[Link]() # Output: Woof!

Class Attributes vs. Data Attributes


Class Attributes: These are attributes that are shared among all instances of a class. They are defined
within the class but outside of any method.
Data Attributes: These are attributes that are specific to each instance of a class. They are defined within
the init method or other instance methods.

Encapsulation
Encapsulation is one of the fundamental principles of object-oriented programming. It refers to the
bundling of data and methods into a single unit (the class), hiding the internal implementation details from

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

37
Expt. No. : Page No. :
Date :

the outside world. This helps to achieve data abstraction and information hiding.

Inheritance
Inheritance is a mechanism in which a new class is based on an existing class, inheriting its attributes and
methods. The new class is called the derived or child class, and the existing class is called the base or
parent class.

Polymorphism
Polymorphism is the ability of objects of different classes to be treated as objects of a common superclass.
This means that a method call on a child class object can be handled by a method in the parent class, even
if the methods have the same name but different implementations.

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

38
Expt. No. : Page No. :
Date :

Sample Experiments:
1. 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.
2. Python program to print each line of a file in reverse order.
3. Python program to compute the number of characters, words and lines in a file.
4. Write a program to create, display, append, insert and reverse the order of the items in the array.
5. Write a program to add, transpose and multiply two matrices.

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

39
Expt. No. : Page No. :
Date :

1. AIM: Write a program to print each line of a file in reverse order.


Create a text file and save it with “[Link]” name

CODE
file = open("[Link]", "r")
x=[Link]()
print(x)
print(x[::-1])
[Link]()

OUTPUT:
This is a python program
margorpnohtyp a sisihT

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

40
Expt. No. : Page No. :
Date :

2. Write a program to compute the number of characters, words and lines in a file.

Create a text file and save it with “[Link]” name

CODE

file_path = '[Link]' # Replace with your file path

# Open the file and read its contents

file = open(file_path, 'r')


lines = [Link]()

# Counting lines, words, and characters


line_count = len(lines)
word_count = sum(len([Link]()) for line in lines)

char_count = sum(len(line) for line in lines)

# Print the results


print("Lines: {},Words: {},Characters: {}".format(line_count,word_count,char_count))

# Close the file


[Link]()

OUTPUT:
Lines: 4,Words: 25,Characters: 114

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

41
Expt. No. : Page No. :
Date :

3. Write a program to create, display, append, insert and reverse the order of the items in the array.
my_array = [1, 2, 3, 4, 5]
def display_array():
print("Current array:", my_array)
print("Initial array:")
display_array()
my_array.append(6)
print("\nAfter appending 6:")
display_array()
my_array.insert(2, 10)
print("\nAfter inserting 10 at index 2:")
display_array()
my_array.reverse()
print("\nAfter reversing the array:")
display_array()

OUTPUT

Initial array:
Current array: [1, 2, 3, 4, 5]
After appending 6:
Current array: [1, 2, 3, 4, 5, 6]
After inserting 10 at index 2:
Current array: [1, 2, 10, 3, 4, 5, 6]
After reversing the array:
Current array: [6, 5, 4, 3, 10, 2, 1]
Final array after user input:
Current array: [6, 5, 4, 3, 10, 2, 1]

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

42
Expt. No. : Page No. :
Date :

4. Write a program to add, transpose and multiply two matrices.

# Define two matrices


matrix_a = [[1, 2],[3,4]]
matrix_b = [[5,6],[7,8]]

# Matrix Addition
rows_a = len(matrix_a)
cols_a = len(matrix_a[0])
rows_b = len(matrix_b)
cols_b = len(matrix_b[0])

# Check if matrices can be added


if rows_a == rows_b and cols_a == cols_b:
sum_matrix = [[0 for _ in range(cols_a)] for _ in range(rows_a)]
for i in range(rows_a):
for j in range(cols_a):
sum_matrix[i][j] = matrix_a[i][j] + matrix_b[i][j]
print("Sum of matrices:")
for row in sum_matrix:
print(row)
else:
print("Matrices cannot be added due to incompatible dimensions.")

# Matrix Transposition
transpose_a = [[0 for _ in range(rows_a)] for _ in range(cols_a)]
for i in range(rows_a):
for j in range(cols_a):
transpose_a[j][i] = matrix_a[i][j]

print("\nTranspose of Matrix A:")


for row in transpose_a:
print(row)

# Matrix Multiplication
if cols_a == rows_b:
product_matrix = [[0 for _ in range(cols_b)] for _ in range(rows_a)]
for i in range(rows_a):
for j in range(cols_b):
for k in range(cols_a):
product_matrix[i][j] += matrix_a[i][k] * matrix_b[k][j]
print("\nProduct of matrices:")
for row in product_matrix:
print(row)
else:
print("Matrices cannot be multiplied due to incompatible dimensions.")

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

43
Expt. No. : Page No. :
Date :

OUTPUT

Sum of matrices:
[6, 8]
[10, 12]

Transpose of Matrix A:
[1, 3]
[2, 4]

Product of matrices:
[19, 22]
[43, 50]

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

44
Expt. No. : Page No. :
Date :

UNIT-5
1. Functional Programming
Introduction
Functional programming is a programming paradigm that focuses on pure functions, immutable data, and
declarative programming. In Python, you can leverage functional programming concepts using built-in
higher-order functions and lambda functions.

Higher-Order Functions
Python’s built-in higher-order functions include map(), filter(), and reduce().
# Using map()
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16, 25]

# Using filter()
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4]

# Using reduce()
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 120

2. JSON and XML in Python


JSON (JavaScript Object Notation)
JSON is a lightweight data interchange format. In Python, you can use the json module to work with JSON
data.
import json

# Serialize a Python object to JSON


data = {"name": "John", "age": 30, "city": "New York"}
json_data = [Link](data)
print(json_data) # Output: {"name": "John", "age": 30, "city": "New York"}

# Deserialize JSON to a Python object


loaded_data = [Link](json_data)
print(loaded_data) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}

XML (Extensible Markup Language)


XML is a markup language for structuring data. In Python, you can use the xml module to work with XML
data.
import [Link] as ET

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

45
Expt. No. : Page No. :
Date :

# Create an XML tree


root = [Link]("root")
child = [Link](root, "child")
[Link] = "Hello, World!"
tree = [Link](root)

# Write the XML tree to a file


[Link]("[Link]")

# Parse an XML file


tree = [Link]("[Link]")
root = [Link]()
print(root[0].text) # Output: Hello, World!

3. NumPy with Python


Introduction
NumPy is a powerful library in Python that provides support for large, multi-dimensional arrays and
matrices, along with a large collection of high-level mathematical functions to operate on these arrays.

NumPy Arrays
import numpy as np

# Create a NumPy array


arr = [Link]([1, 2, 3, 4, 5])
print(arr) # Output: [1 2 3 4 5]

# Perform operations on NumPy arrays


print(arr + 2) # Output: [3 4 5 6 7]
print(arr * 2) # Output: [2 4 6 8 10]
print([Link](arr)) # Output: [1. 1.41421356 1.73205081 2. 2.23606798]

NumPy Functions
NumPy provides a wide range of functions for working with arrays, such as sum(), mean(), std(), sort(),
and more.
# NumPy functions
print([Link](arr)) # Output: 15
print([Link](arr)) # Output: 3.0
print([Link](arr)) # Output: 1.4142135623730951
print([Link](arr)) # Output: [1 2 3 4 5]

4. Pandas
Introduction
Pandas is a powerful open-source library in Python that provides high-performance, easy-to-use data
structures and data analysis tools. The two primary data structures in Pandas are Series and DataFrame.

Series

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

46
Expt. No. : Page No. :
Date :

A Pandas Series is a one-dimensional labeled array capable of holding data of any data type.
import pandas as pd

# Creating a Pandas Series


s = [Link]([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e'])
print(s)
# Output:
#a 1
#b 2
#c 3
#d 4
#e 5
# dtype: int64

DataFrame
A Pandas DataFrame is a two-dimensional labeled data structure, with rows and columns.
# Creating a Pandas DataFrame
data = {
"Name": ["John", "Jane", "Bob"],
"Age": [30, 25, 35],
"City": ["New York", "London", "Paris"]
}
df = [Link](data)
print(df)
# Name Age City
# 0 John 30 New York
# 1 Jane 25 London
# 2 Bob 35 Paris

Pandas Functions
Pandas provides a wide range of functions and methods for data manipulation, analysis, and visualization,
such as head(), describe(), groupby(), plot(), and more.
# Pandas functions
print([Link]()) # Display the first 5 rows
print([Link]()) # Get summary statistics
print([Link]("City").size()) # Group by city and get the count
[Link](kind="bar", x="Name", y="Age") # Create a bar plot

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

47
Expt. No. : Page No. :
Date :

Sample Experiments:
1. Python program to check whether a JSON string contains complex object or not.
2. Python Program to demonstrate NumPy arrays creation using array () function.
3. Python program to demonstrate use of ndim, shape, size, dtype.
4. Python program to demonstrate basic slicing, integer and Boolean indexing.
5. Python program to find min, max, sum, cumulative sum of array
6. 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
7. 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

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

48
Expt. No. : Page No. :
Date :

1. Python program to check whether a JSON string contains complex object or not.

import json
def is_complex_object(json_string):
# Check if JSON string is valid
if not json_string.startswith('{') and not json_string.startswith('['):
return False
# Load JSON string into Python object
data = [Link](json_string)
# Check if object is dictionary or list
if isinstance(data, dict):
# Check for nested objects or lists
return any(isinstance(value, (dict, list)) for value in [Link]())
elifisinstance(data, list):
# Check for nested objects or lists
return any(isinstance(item, (dict, list)) for item in data)
else:
return False

# Test cases
json_strings = [
'{"key": "value"}', # Simple object
'{"key": {"nested": "value"}}', # Complex object
'[{"key": "value"}, {"key": "value"}]', # Complex object (list)
'{"key": ["value1", "value2"]}', # Complex object (list)
'{"key": [{"nested": "value"}]}', # Complex object (nested list)
'Invalid JSON', # Invalid JSON
'' # Empty string
]

for json_string in json_strings:


result = is_complex_object(json_string)
print(f'JSON String: {json_string}, Complex Object: {result}')

OUPUT

JSON String: {"key": "value"}, Complex Object: False


JSON String: {"key": {"nested": "value"}}, Complex Object: True
JSON String: [{"key": "value"}, {"key": "value"}], Complex Object: True
JSON String: {"key": ["value1", "value2"]}, Complex Object: True
JSON String: {"key": [{"nested": "value"}]}, Complex Object: True
JSON String: Invalid JSON, Complex Object: False
JSON String: , Complex Object: False

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

49
Expt. No. : Page No. :
Date :

2. NumPy Array Creation using array() Function

import numpy as np

# 1. From List
l1 = list(map(int, input("Enter the list elements separated by space: ").split()))
numpy_array = [Link](l1)
print("Array from List:\n", numpy_array)

# 2. From Tuple
t = (6, 7, 8, 9, 10)
numpy_array = [Link](t)
print("\nArray from Tuple:\n", numpy_array)

# 3. From Nested List (2D Array)


data = [[1, 2], [3, 4], [5, 6]]
numpy_array = [Link](data)
print("\n2D Array from Nested List:\n", numpy_array)

# 4. Specifying Data Type


data_list = [1, 2, 3, 4, 5]
numpy_array = [Link](data_list, dtype=float)
print("\nArray with Float Data Type:\n", numpy_array)

# 5. From Existing Array


existing_array = [Link]([1, 2, 3])
new_array = [Link](existing_array) # Use [Link]() instead of [Link]()
print("\nArray from Existing Array:\n", new_array)

OUTPUT

Enter the list elements separated by space: 1 2 3 4 5


Array from List:
[1 2 3 4 5]
Array from Tuple:
[ 6 7 8 9 10]
2D Array from Nested List:
[[1 2]
[3 4]
[5 6]]
Array with Float Data Type:
[1. 2. 3. 4. 5.]
Array from Existing Array:
[1 2 3]

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

50
Expt. No. : Page No. :
Date :

3. Python program to demonstrate use of ndim, shape, size, dtype.

import numpy as np
# Create arrays
array_1d = [Link]([1, 2, 3, 4, 5])
array_2d = [Link]([[1, 2], [3, 4], [5, 6]])
array_3d = [Link]([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
# Display array attributes
arrays = [array_1d, array_2d, array_3d]

for i in range(len(arrays)):
array = arrays[i]
print(f"\nArray {i+1} Attributes:")
print(f"Dimensions (ndim): {[Link]}")
print(f"Shape: {[Link]}")
print(f"Size (elements): {[Link]}")
print(f"Data Type (dtype): {[Link]}")

OUTPUT

Array 1 Attributes:
Dimensions (ndim): 1
Shape: (5,)
Size (elements): 5
Data Type (dtype): int64

Array 2 Attributes:
Dimensions (ndim): 2
Shape: (3, 2)
Size (elements): 6
Data Type (dtype): int64

Array 3 Attributes:
Dimensions (ndim): 3
Shape: (2, 2, 2)
Size (elements): 8
Data Type (dtype): int64

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

51
Expt. No. : Page No. :
Date :

4. Python program to demonstrate basic slicing, integer and Boolean indexing.

import numpy as np
# Create a sample NumPy array
array = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9])
# Basic Slicing
print("Basic Slicing:")
print(array[1:5]) # Elements from index 1 to 4
print(array[3:]) # Elements from index 3 onwards
print(array[:5]) # Elements up to index 4
print(array[:]) # All elements
# Integer Indexing
print("\nInteger Indexing:")
print(array[3]) # Element at index 3
print(array[[3, 5, 7]]) # Elements at indices 3, 5, 7
# Boolean Indexing
bool_index = [Link]([True, False, True, False, True, False, True, False, True])
print("\nBoolean Indexing:")
print(array[bool_index]) # Elements where bool_index is True
# Advanced Indexing
print("\nAdvanced Indexing:")
indices = [Link]([3, 5, 7])
print(array[indices]) # Elements at specified indices
# Negative Indexing
print("\nNegative Indexing:")
print(array[-3:]) # Last 3 elements
print(array[-5:-1]) # Elements from 5th last to 2nd last

OUTPUT

Basic Slicing:
[2 3 4 5]
[4 5 6 7 8 9]
[1 2 3 4 5]
[1 2 3 4 5 6 7 8 9]
Integer Indexing:
4
[4 6 8]
Boolean Indexing:
[1 3 5 7 9]
Advanced Indexing:
[4 6 8]
Negative Indexing:
[7 8 9]
[5 6 7 8]

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

52
Expt. No. : Page No. :
Date :

5. Python program to find min, max, sum, cumulative sum of array

import numpy as np
# Create a sample NumPy array
array = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9])

# Array Statistics
print("Array Statistics:")
print("Minimum:", [Link](array))
print("Maximum:", [Link](array))
print("Sum:", [Link](array))
print("Cumulative Sum:", [Link](array))

OUTPUT

Array Statistics:
Minimum: 1
Maximum: 9
Sum: 45
Cumulative Sum: [ 1 3 6 10 15 21 28 36 45]

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

53
Expt. No. : Page No. :
Date :

6. 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

import pandas as pd
# Create a dictionary with five keys
data_dict = {
'Name': ['Nitya', 'Nithika', 'Manasvi', 'Dikshitha', 'Reshma', 'Nimisha', 'Bhavishya'],
'Age': [25, 30, 28, 22, 35, 27, 24],
'Country': ['USA', 'UK', 'UK', 'Australia', 'Germany', 'USA', 'UK'],
'Score': [85, 90, 78, 95, 89, 84, 91],
'Grade': ['A', 'A', 'B', 'A', 'A', 'B', 'A']
}

df = [Link](data_dict)

print(" Display DataFrame")


print(df)
print("# Display first five rows")
print([Link](5))
print("Select rows where Country == 'USA'")
print(df[df['Country'] == 'USA'])
print("Select rows where Age > 28")
print(df[df['Age'] > 28])

OUTPUT

Display DataFrame
Name Age Country Score Grade
0 Nitya 25 USA 85 A
1 Nithika 30 UK 90 A
2 Manasvi 28 UK 78 B
3 Dikshitha 22 Australia 95 A
4 Reshma 35 Germany 89 A
5 Nimisha 27 USA 84 B
6 Bhavishya 24 UK 91 A

# Display first five rows


Name Age Country Score Grade
0 Nitya 25 USA 85 A
1 Nithika 30 UK 90 A
2 Manasvi 28 UK 78 B
3 Dikshitha 22 Australia 95 A
4 Reshma 35 Germany 89 A

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

54
Expt. No. : Page No. :
Date :

Select rows where Country == 'USA'


Name Age Country Score Grade
0 Nitya 25 USA 85 A
5 Nimisha 27 USA 84 B

Select rows where Age > 28


Name Age Country Score Grade
1 Nithika 30 UK 90 A
4 Reshma 35 Germany 89 A

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

55
Expt. No. : Page No. :
Date :

7. 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

import [Link] as plt


import pandas as pd

# Create a dictionary with five keys


data_dict = {
'Name': ['John', 'Anna', 'Peter', 'Linda', 'Tom', 'Lisa', 'Jim', 'Kate', 'Sam', 'Nicole'],
'Age': [25, 30, 28, 22, 35, 26, 29, 31, 27, 24],
'Country': ['USA', 'UK', 'Australia', 'Germany', 'USA', 'UK', 'Australia', 'Germany', 'USA', 'UK'],
'Score': [85, 90, 78, 92, 88, 76, 95, 89, 84, 91],
'Grade': ['A', 'A', 'B', 'A', 'B', 'B', 'A', 'A', 'B', 'A']
}

# Convert dictionary to Pandas DataFrame


df = [Link](data_dict)

# Select 'Age' and 'Score' columns


selected_df = df[['Age', 'Score']]

## Scatter Plot
[Link](figsize=(8,6))
[Link](selected_df['Age'], selected_df['Score'])
[Link]('Age vs Score')
[Link]('Age')
[Link]('Score')
[Link](True)
[Link]()

## Line Plot
[Link](figsize=(8,6))
[Link](selected_df['Age'], selected_df['Score'], marker='o')
[Link]('Age vs Score')
[Link]('Age')
[Link]('Score')
[Link](True)
[Link]()

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

56
Expt. No. : Page No. :
Date :

OUTPUT:

Aditya College of Engineering & Technology, Surampalem (A) Reg. No.

57

You might also like