Python Programming Lab Manual II-i
Python Programming Lab Manual II-i
II [Link] I SEM
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
1
Expt. No. : Page No. :
Date :
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
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)
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.
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.
4
Expt. No. : Page No. :
Date :
OUTPUT
5
Expt. No. : Page No. :
Date :
OUTPUT
6
Expt. No. : Page No. :
Date :
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
7
Expt. No. : Page No. :
Date :
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
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
a -= 1
print("a -= 1:", a)
a *= 3
print("a *= 3:", a)
a /= 2
print("a /= 2:", a)
a //= 2
9
Expt. No. : Page No. :
Date :
a **= 2
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)
10
Expt. No. : Page No. :
Date :
print("~a:", ~a)
~a: -11
a << 2: 40
a >> 2: 2
PROGRAM
a = 10
b = 20
max_value = a if a > b else b
print("Maximum value is:", max_value)
OUTPUT
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
11
Expt. No. : Page No. :
Date :
PROGRAM
a = 10
b = 10
c = [1, 2, 3]
d = [1, 2, 3]
print("a is b:", a is b) # is
OUTPUT
a is b: True
a is not b: False
c is d: False
c is not d: True
12
Expt. No. : Page No. :
Date :
OUTPUT
Addition is : (3+5j)
Subtraction is : (1+1j)
Multiplication is : (-4+7j)
13
Expt. No. : Page No. :
Date :
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
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
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:
15
Expt. No. : Page No. :
Date :
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 Formatting
%-formatting:
"Hello, %s" % "World"
[Link]():
"Hello, {}".format("World")
f-strings (Python 3.6+):
16
Expt. No. : Page No. :
Date :
name = "World"
f"Hello, {name}"
3. Lists
# Basic operations
length = len(numbers) # Length
concat = [1, 2] + [3, 4] # Concatenation
repeat = [0] * 3 # Repetition
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
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
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.
19
Expt. No. : Page No. :
Date :
def name():
return "John","Armin"
OUTPUT
('John', 'Armin')
John Armin
20
Expt. No. : Page No. :
Date :
Program_1
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
21
Expt. No. : Page No. :
Date :
[Link] a program to find the length of the string without using any library functions.
OUTPUT
22
Expt. No. : Page No. :
Date :
OUTPUT
23
Expt. No. : Page No. :
Date :
# 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
24
Expt. No. : Page No. :
Date :
OUTPUT
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()
# Modifying values
student["age"] = 21
student["subject"] = "Python" # Adding new key-value pair
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
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()
# Repetition
repeated = tuple1 * 2 # (1, 2, 1, 2)
# Dictionary to Tuple
my_dict = {"a": 1, "b": 2}
key_tuple = tuple(my_dict.keys())
27
Expt. No. : Page No. :
Date :
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 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
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.
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.
Output:
('Ram', 20, 'Andhra pradesh', 'JNTUK university', 'john', 22, 'Canada', 'Alberta university')
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"
Output:
Number of vowels: 3
31
Expt. No. : Page No. :
Date :
# Sample dictionary
my_dict = {"name": "Alice", "age": 25, "address": "123 Main St"}
# Key to check
key_to_check = "college"
Output:
32
Expt. No. : Page No. :
Date :
# Existing dictionary
new_key = "college"
new_value = "JNTUK"
my_dict[new_key] = new_value
OUTPUT:
Updated dictionary: {'name': 'Ram', 'age': 25, 'address': 'Kakinada', 'college': 'JNTUK'}
33
Expt. No. : Page No. :
Date :
# 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
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.
Pickle Module
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
36
Expt. No. : Page No. :
Date :
if [Link]("[Link]"):
print("File exists")
else:
print("File does not exist")
def bark(self):
print("Woof!")
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
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.
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.
39
Expt. No. : Page No. :
Date :
CODE
file = open("[Link]", "r")
x=[Link]()
print(x)
print(x[::-1])
[Link]()
OUTPUT:
This is a python program
margorpnohtyp a sisihT
40
Expt. No. : Page No. :
Date :
2. Write a program to compute the number of characters, words and lines in a file.
CODE
OUTPUT:
Lines: 4,Words: 25,Characters: 114
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]
42
Expt. No. : Page No. :
Date :
# Matrix Addition
rows_a = len(matrix_a)
cols_a = len(matrix_a[0])
rows_b = len(matrix_b)
cols_b = len(matrix_b[0])
# 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]
# 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.")
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]
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
45
Expt. No. : Page No. :
Date :
NumPy Arrays
import numpy as np
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
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
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
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
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
]
OUPUT
49
Expt. No. : Page No. :
Date :
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)
OUTPUT
50
Expt. No. : Page No. :
Date :
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
51
Expt. No. : Page No. :
Date :
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]
52
Expt. No. : Page No. :
Date :
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]
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)
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
54
Expt. No. : Page No. :
Date :
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
## 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]()
56
Expt. No. : Page No. :
Date :
OUTPUT:
57