Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Python Programming Lab Manual

Python

Uploaded by

myr4112
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Python Programming Lab Manual

Python

Uploaded by

myr4112
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

1) WRITE A PROGRAM TO FIND THE LARGEST ELEMENT

AMONG THREE NUMBERS USING PYTHON

Certainly! To find the largest element among three numbers in Python, you
can use the built-in max() function, which simplifies the task. Here's a
straightforward example of how you can do this:

# Function to find the largest of three numbers

def find largest(a, b, c):

Return max (a, b, c)

# Input three numbers from the user

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

num2 = float (input ("Enter the second number: "))

num3 = float (input("Enter the third number: "))

# Find and print the largest number

largest = find largest(num1, num2, num3)

Print (f"The largest number among {num1}, {num2}, and {num3} is


{largest}.")

Explanation:

1. Define a Function: find largest (a, b, c) takes three arguments and


returns the maximum of these values using the max () function.
2. Input Numbers: The program prompts the user to input three
numbers. These are converted to floats to handle decimal values.
3. Find and Display the Largest Number: It calls the find largest ()
function with the input values and prints the result.

Example Usage:

If the user inputs:

Enter the first number: 10


Enter the second number: 20

Enter the third number: 15

The output will be:

The output will be:

The largest number among 10.0, 20.0, and 15.0 is 20.0.

Feel free to use or modify this code according to your needs!

1.(A)WRITE A PROGRAM TO DISPLAY ALL PRIME NUMBERS


WITHIN AN INTERVAL USING PYTHON

ure! To display all prime numbers within a given interval in Python, you
can follow these steps:

1. Define a function to check if a number is prime.


2. Iterate over the interval and use the function to check each number.
3. Print the prime numbers.

Here is a Python program that accomplishes this:

def is_prime(n):

"""Check if a number is a prime number."""

if n <= 1:

return False

if n <= 3:

return True

if n % 2 == 0 or n % 3 == 0:

return False

i=5

while i * i <= n:

if n % i == 0 or n % (i + 2) == 0:
return False

i += 6

return True

def display_primes(start, end):

"""Display all prime numbers within a given interval."""

print(f"Prime numbers between {start} and {end}:")

for num in range(start, end + 1):

if is_prime(num):

print(num, end=' ')

print() # For newline after the list of primes

# Input interval from the user

start = int(input("Enter the start of the interval: "))

end = int(input("Enter the end of the interval: "))

# Display prime numbers within the interval

display_primes(start, end)

Explanation:

1. is_prime(n) Function:
o Checks if a number n is prime.
o Handles special cases (e.g., numbers less than or equal to 1, and
multiples of 2 and 3).
o Uses trial division up to the square root of n, with
optimizations for efficiency.
2. display_primes(start, end) Function:
o Iterates through the range from start to end.
o Uses the is_prime function to check if each number is prime
and prints it.
3. User Input:
o The program prompts the user to input the start and end of the
interval.
o Calls display_primes with the user-provided interval.

Example Usage:

If the user inputs:

Enter the start of the interval: 10

Enter the end of the interval: 30

The output will be:

Prime numbers between 10 and 30:

11 13 17 19 23 29

This program effectively lists all prime numbers within the specified range.
Feel free to adjust it as needed!

2).WRITE A PROGRAM TO SWAP TWO NUMBERS WITHOUT


USING A TEMPORARY VARIABLE USING PYTHON
PROGRAMMING

ertainly! You can swap two numbers without using a temporary variable
by utilizing arithmetic operations or tuple unpacking. Below are two
methods to achieve this in Python:

Method 1: Using Arithmetic Operations

Here's a Python program that swaps two numbers using arithmetic


operations:

# Function to swap two numbers using arithmetic operations

def swap_numbers_arithmetic(a, b):

print(f"Before swap: a = {a}, b = {b}")


# Swap using arithmetic operations

a=a+b

b=a-b

a=a-b

print(f"After swap: a = {a}, b = {b}")

return a, b

# Input two numbers from the user

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

num2 = float(input("Enter the second number: "))

# Swap and display the results

num1, num2 = swap_numbers_arithmetic(num1, num2)

Method 2: Using Tuple Unpacking

Here's a Python program that swaps two numbers using tuple unpacking:

# Function to swap two numbers using tuple unpacking

def swap_numbers_tuple(a, b):

print(f"Before swap: a = {a}, b = {b}")

# Swap using tuple unpacking


a, b = b, a

print(f"After swap: a = {a}, b = {b}")

return a, b

# Input two numbers from the user

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

num2 = float(input("Enter the second number: "))

# Swap and display the results

num1, num2 = swap_numbers_tuple(num1, num2)

Explanation:

1. Method 1: Arithmetic Operations


o Addition and Subtraction: This method uses addition and
subtraction to swap the values. It works by first adding the two
numbers together, then subtracting one of the numbers from
the sum to get the other number, and finally subtracting the
new value from the sum to get the original number.
2. Method 2: Tuple Unpacking
o Tuple Unpacking: Python allows multiple assignments using
tuple unpacking. This method is more concise and preferred
for its readability and simplicity. You simply assign b to a and
a to b in one line.

Both methods effectively swap the values of a and b without using a


temporary variable. Choose the method that best suits your preference or
the context of your problem!

2(A) DEMONSTRATE THE FOLLOWING OPERATORS IN


OPERATORS IN PYTHON WITH SUITABLE EXAMPLES
I)ARTIHEMETIC OPERATORS II)RELATIONAL OPERATORS
III)ASSIGNMENT OPERATORS IV)LOGICAL OPERATORS V) BIT
WISE OPERATORS

Certainly! Below is a demonstration of each category of operators in


Python with suitable examples.

I) Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations.

# Arithmetic Operators

a = 10

b=5

# Addition

add = a + b

print(f"Addition: {a} + {b} = {add}")

# Subtraction

sub = a - b

print(f"Subtraction: {a} - {b} = {sub}")

# Multiplication

mul = a * b

print(f"Multiplication: {a} * {b} = {mul}")

# Division

div = a / b

print(f"Division: {a} / {b} = {div}")


# Floor Division

floordiv = a // b

print(f"Floor Division: {a} // {b} = {floordiv}")

# Modulus

mod = a % b

print(f"Modulus: {a} % {b} = {mod}")

# Exponentiation

exp = a ** b

print(f"Exponentiation: {a} ** {b} = {exp}")

# Arithmetic Operators

a = 10

b=5

# Addition

add = a + b

print(f"Addition: {a} + {b} = {add}")

# Subtraction

sub = a - b

print(f"Subtraction: {a} - {b} = {sub}")


# Multiplication

mul = a * b

print(f"Multiplication: {a} * {b} = {mul}")

# Division

div = a / b

print(f"Division: {a} / {b} = {div}")

# Floor Division

floordiv = a // b

print(f"Floor Division: {a} // {b} = {floordiv}")

# Modulus

mod = a % b

print(f"Modulus: {a} % {b} = {mod}")

# Exponentiation

exp = a ** b

print(f"Exponentiation: {a} ** {b} = {exp}")

II) Relational Operators

Relational operators are used to compare values.

# Relational Operators

x = 15

y = 10
# Equal to

print(f"Equal to: {x} == {y} is {x == y}")

# Not equal to

print(f"Not equal to: {x} != {y} is {x != y}")

# Greater than

print(f"Greater than: {x} > {y} is {x > y}")

# Less than

print(f"Less than: {x} < {y} is {x < y}")

# Greater than or equal to

print(f"Greater than or equal to: {x} >= {y} is {x >= y}")

# Less than or equal to

print(f"Less than or equal to: {x} <= {y} is {x <= y}")

III) Assignment Operators

Assignment operators are used to assign values to variables.

# Assignment Operators

a = 10

b=5
# Basic assignment

a=b

print(f"Basic assignment: a = {a}")

# Add and assign

a += b

print(f"Add and assign: a += b -> a = {a}")

# Subtract and assign

a -= b

print(f"Subtract and assign: a -= b -> a = {a}")

# Multiply and assign

a *= b

print(f"Multiply and assign: a *= b -> a = {a}")

# Divide and assign

a /= b

print(f"Divide and assign: a /= b -> a = {a}")

# Modulus and assign

a %= b

print(f"Modulus and assign: a %= b -> a = {a}")


# Exponent and assign

a **= b

print(f"Exponent and assign: a **= b -> a = {a}")

# Floor divide and assign

a //= b

print(f"Floor divide and assign: a //= b -> a = {a}")

IV) Logical Operators

Logical operators are used to perform logical operations.

# Logical Operators

x = True

y = False

# AND operator

print(f"AND operator: {x} and {y} = {x and y}")

# OR operator

print(f"OR operator: {x} or {y} = {x or y}")

# NOT operator

print(f"NOT operator: not {x} = {not x}")

print(f"NOT operator: not {y} = {not y}")

V) Bitwise Operators
Bitwise operators are used to perform operations on binary representations
of integers.

# Bitwise Operators

a = 12 # 1100 in binary

b = 7 # 0111 in binary

# AND operator

bitwise_and = a & b

print(f"Bitwise AND: {a} & {b} = {bitwise_and}")

# OR operator

bitwise_or = a | b

print(f"Bitwise OR: {a} | {b} = {bitwise_or}")

# XOR operator

bitwise_xor = a ^ b

print(f"Bitwise XOR: {a} ^ {b} = {bitwise_xor}")

# Complement operator

bitwise_not = ~a

print(f"Bitwise NOT: ~{a} = {bitwise_not}")

# Left shift operator

left_shift = a << 2

print(f"Left shift: {a} << 2 = {left_shift}")


# Right shift operator

right_shift = a >> 2

print(f"Right shift: {a} >> 2 = {right_shift}")

Summary

 Arithmetic Operators perform basic arithmetic operations.


 Relational Operators compare values and return boolean results.
 Assignment Operators assign values to variables and can perform
operations simultaneously.
 Logical Operators perform logical operations and return boolean
results.
 Bitwise Operators operate on binary representations of integers.

Feel free to run these code snippets to see the operators in action!

3) WRITE A PROGRAM TO ADD AND MULTIPLY


COMPLEX NUMBERS USING PYTHON PROGRAMING
 Certainly! In Python, complex numbers are represented with the
complex type, and you can perform arithmetic operations on them
just like with real numbers. Below is a Python program that
demonstrates how to add and multiply complex numbers.
 # Function to add two complex numbers
 def add_complex_numbers(c1, c2):
 return c1 + c2

 # Function to multiply two complex numbers
 def multiply_complex_numbers(c1, c2):
 return c1 * c2

 # Input complex numbers from the user
 # User inputs will be in the form "a+bj" where a and b are real
numbers
 complex1 = complex(input("Enter the first complex number (in the
form a+bj): "))
 complex2 = complex(input("Enter the second complex number (in
the form a+bj): "))

 # Perform addition and multiplication
 sum_result = add_complex_numbers(complex1, complex2)
 product_result = multiply_complex_numbers(complex1, complex2)

 # Display the results
 print(f"The sum of {complex1} and {complex2} is {sum_result}")
 print(f"The product of {complex1} and {complex2} is
{product_result}")

Explanation:

1. Functions for Operations:


o add_complex_numbers(c1, c2): Adds two complex numbers.
o multiply_complex_numbers(c1, c2): Multiplies two complex
numbers.
2. User Input:
o The user is prompted to input two complex numbers in the
form a+bj, where a and b are real numbers.
3. Arithmetic Operations:
o Addition: Performed using the + operator.
o Multiplication: Performed using the * operator.
4. Display Results:
o The results of the addition and multiplication are printed.

Example Usage:

If the user inputs:

Enter the first complex number (in the form a+bj): 2+3j

Enter the second complex number (in the form a+bj): 1+4j

The output will be:

The sum of (2+3j) and (1+4j) is (3+7j)

The product of (2+3j) and (1+4j) is (-10+11j)

3.(A) WRITE A PROGRAM TO PRINT MULTIPLICATION TABLE OF


A GIVEN NUMBER USING PYTHON PROGRAMMING
Certainly! To print the multiplication table of a given number using
Python, you can use a simple loop. Here's a program that accomplishes
this:

Python
# Function to print the multiplication table of a given number
def print_multiplication_table(number, up_to=10):
print(f"Multiplication table for {number}:")
for i in range(1, up_to + 1):
result = number * i
print(f"{number} x {i} = {result}")

# Input number from the user


num = int(input("Enter a number to print its multiplication table: "))

# Optionally, you can change the range (up_to) to print more or fewer lines
print_multiplication_table(num)

Explanation:

1. Function Definition:
o print_multiplication_table(number, up_to=10): This function
prints the multiplication table for the given number up to
up_to times (default is 10). You can modify up_to to change the
range of the multiplication table if needed.
2. Input Number:
o The user is prompted to input a number for which the
multiplication table will be generated.
3. Loop:
o The for loop iterates from 1 to up_to, calculating the product of
the given number and the loop index (i), and prints the result in
a formatted manner.
4. Output:
o The multiplication table is printed line by line in the format
number x i = result.

Example Usage:

If the user inputs 5, the output will be:

Enter a number to print its multiplication table: 5


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

This program will print the multiplication table of any number entered by
the user, and you can adjust the range if you need a longer or shorter table.

4) WRITE A PROGRAM TO DEFINE A FUNCTION WITH MULTIPLE


RETURN VALUES USING PYTHON PROGRAMMING

Example Program

Let's create a function that takes two numbers as input and returns both
their sum and their product.

def calculate_sum_and_product(a, b):


"""
This function takes two numbers and returns their sum and product.

Parameters:
a (int or float): The first number
b (int or float): The second number

Returns:
tuple: A tuple containing the sum and the product of the two numbers
"""
# Calculate sum and product
sum_result = a + b
product_result = a * b

# Return both values as a tuple


return sum_result, product_result

# Example usage
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Call the function and get the results


sum_result, product_result = calculate_sum_and_product(num1, num2)

# Print the results


print(f"The sum of {num1} and {num2} is {sum_result}.")
print(f"The product of {num1} and {num2} is {product_result}.")

Explanation:

1. Function Definition:
o calculate_sum_and_product(a, b): This function takes two
parameters a and b. It calculates their sum and product, then
returns both results as a tuple (sum_result, product_result).
2. Return Multiple Values:
o By returning the values separated by commas, Python
automatically packs these values into a tuple. When the
function is called, the caller can unpack this tuple into
individual variables.
3. Example Usage:
o The user is prompted to input two numbers. The function is
called with these numbers, and the results (sum and product)
are unpacked and printed.

Example Output:

If the user inputs 4 and 5, the output will be:

Enter the first number: 4


Enter the second number: 5
The sum of 4.0 and 5.0 is 9.0.
The product of 4.0 and 5.0 is 20.0.

This program shows how to define a function that returns multiple values
and how to handle these return values effectively.

4.A) WRITE APROGRAM TO DEFINE A FUNCTION USING


DEFAULT ARGUMENTS

Here's an example of a Python program that defines a function using


default arguments:
def greet(name, greeting="Hello", punctuation="!"):

"""

Function to greet someone with a given name, greeting, and punctuation.

The greeting and punctuation have default values.

"""

return f"{greeting}, {name}{punctuation}"

# Examples of calling the function

print(greet("Alice")) # Uses default greeting and punctuation

print(greet("Bob", "Hi")) # Uses default punctuation

print(greet("Charlie", "Good morning", ".")) # No default values used

Explanation:

 The function greet takes three arguments: name, greeting, and


punctuation.
 The greeting and punctuation arguments have default values of
"Hello" and "!", respectively.
 When you call the function, if you don't provide values for greeting
or punctuation, the default values are used.
 The function returns a string formatted as greeting, name! (or with
other punctuation if provided).

Output:

Hello, Alice!

Hi, Bob!

Good morning, Charlie.

In these examples:

 greet("Alice") uses the default values for greeting and punctuation.


 greet("Bob", "Hi") uses the default value for punctuation but
overrides greeting.
 greet("Charlie", "Good morning", ".") overrides both defaults.

5) WRITE A PROGRAM TO FIND THE LENGTH OF THE STRING


WITHOUT USING ANY LIBRARY FUNCTIONS.

Here's a Python program that finds the length of a string without using any
built-in functions like len():

def find_length(input_string):

# Initialize a counter variable to 0

length = 0

# Iterate through each character in the string

for char in input_string:

length += 1 # Increment the counter by 1 for each character

return length

# Example usage

string = "Hello, World!"

length_of_string = find_length(string)

print(f"The length of the string '{string}' is: {length_of_string}")

Explanation:

 The find_length function takes an input string as its argument.


 It initializes a counter variable length to 0.
 It then iterates over each character in the input string using a for
loop.
 For each character in the string, it increments the length counter by
1.
 After the loop finishes, the function returns the final value of length,
which is the length of the string.
Output:

The length of the string 'Hello, World!' is: 13

This program effectively counts the number of characters in the string


without using any built-in functions.

5.(A) WRITE A PROGRAM TO CHECK IF THE SUBSTRING IN


PRESENT IN A GIVEN STRING OR NOT

Here's a Python program to check if a substring is present in a given string


without using any built-in functions like in:

def is_substring(main_string, sub_string):

# Get the lengths of both the main string and the substring

len_main = len(main_string)

len_sub = len(sub_string)

# Iterate over the main string up to the point where a match is possible

for i in range(len_main - len_sub + 1):

# Check if the substring matches the part of the main string

match = True

for j in range(len_sub):

if main_string[i + j] != sub_string[j]:

match = False

break

# If match is still True, substring is found

if match:
return True

# If no match was found, return False

return False

# Example usage

main_string = "Hello, World!"

sub_string = "World"

if is_substring(main_string, sub_string):

print(f"The substring '{sub_string}' is present in the main string.")

else:

print(f"The substring '{sub_string}' is NOT present in the main string.")

Explanation:

 The is_substring function takes two arguments: main_string (the


string to search within) and sub_string (the string to search for).
 The lengths of both the main string and the substring are calculated.
 The outer loop iterates through main_string, checking slices of the
string that are the same length as sub_string.
 The inner loop checks if the characters in sub_string match the
corresponding characters in main_string.
 If all characters match, the function returns True, indicating that the
substring is present.
 If no match is found after all iterations, the function returns False.

Output:

The substring 'World' is present in the main string.

This program manually checks if a substring is present in the given string


without using any built-in substring functions.
6.WRITE A PROGRAM TO PERFORM THE GIVEN OPERATIONS ON
A LIST I) ADDITION II) INSERTION III) SLICING

Here’s a Python program that demonstrates how to perform addition,


insertion, and slicing operations on a list:

# Define an initial list

my_list = [1, 2, 3, 4, 5]

# I) Addition: Adding an element to the end of the list

my_list.append(6)

print("After addition:", my_list)

# II) Insertion: Inserting an element at a specific position

my_list.insert(2, 99) # Insert 99 at index 2

print("After insertion:", my_list)

# III) Slicing: Slicing the list to get a sub-list

sliced_list = my_list[1:4] # Get elements from index 1 to 3 (4 is not


included)

print("After slicing:", sliced_list)

Explanation:

1. Addition:
o The append() method adds an element to the end of the list.
o In this example, the number 6 is added to the list.
2. Insertion:
o The insert() method inserts an element at a specified index in
the list.
o In this example, the number 99 is inserted at index 2.
3. Slicing:
o Slicing is used to get a sub-list from the original list.
o The syntax my_list[start:end] is used, where start is the
starting index (inclusive) and end is the ending index
(exclusive).
o In this example, the slice from index 1 to 3 is taken, resulting in
a sub-list.

Output:

After addition: [1, 2, 3, 4, 5, 6]

After insertion: [1, 2, 99, 3, 4, 5, 6]

After slicing: [2, 99, 3]

This program demonstrates how to manipulate a list by adding elements,


inserting elements at a specific position, and extracting parts of the list
using slicing.

6.(A) WRITE A PROGRAM TO PERFORM ANY 5 BUILT IN


PERFORM ANY 5 BUILT IN FUNCTION BY TAKING ANY LIST

Here's a Python program that demonstrates five built-in functions on a list:

# Define an initial list

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

# 1) len(): Get the length of the list

length = len(my_list)

print("Length of the list:", length)

# 2) max(): Find the maximum element in the list

maximum = max(my_list)

print("Maximum element in the list:", maximum)


# 3) min(): Find the minimum element in the list

minimum = min(my_list)

print("Minimum element in the list:", minimum)

# 4) sum(): Calculate the sum of all elements in the list

total_sum = sum(my_list)

print("Sum of all elements in the list:", total_sum)

# 5) sorted(): Return a new list with the elements sorted in ascending order

sorted_list = sorted(my_list)

print("Sorted list:", sorted_list)

Explanation:

1. len():
o Returns the number of elements in the list.
o Example: len(my_list) returns 5.
2. max():
o Returns the largest element in the list.
o Example: max(my_list) returns 50.
3. min():
o Returns the smallest element in the list.
o Example: min(my_list) returns 10.
4. sum():
o Calculates the sum of all elements in the list.
o Example: sum(my_list) returns 150.
5. sorted():
o Returns a new list with the elements sorted in ascending order.
o Example: sorted(my_list) returns [10, 20, 30, 40, 50].

Output:

Length of the list: 5

Maximum element in the list: 50


Minimum element in the list: 10

Sum of all elements in the list: 150

Sorted list: [10, 20, 30, 40, 50]

This program showcases the use of five built-in functions (len, max, min,
sum, and sorted) on a list in Python, each of which serves a different
purpose in list manipulation.

7.WRITE A PROGRAM TO CREATE TUPLES


(NAME,AGE,ADDRESS,COLLEGE) FOR ATLEAST TWO NUMBERS
AND CONCATERATE THE TUPLES AND PRINT THE
CONCATENATE TUPLES

Here's a Python program that creates tuples with the fields (name, age,
address, college) for at least two members, concatenates the tuples, and
prints the concatenated tuple:

# Define the first tuple (name, age, address, college)

member1 = ("Alice", 20, "123 Maple Street", "University of Python")

# Define the second tuple (name, age, address, college)

member2 = ("Bob", 22, "456 Oak Avenue", "Python State College")

# Concatenate the two tuples

concatenated_tuple = member1 + member2

# Print the concatenated tuple

print("Concatenated tuple:", concatenated_tuple)

Explanation:

 Tuple Creation:
o Two tuples member1 and member2 are created, each
containing four elements: name, age, address, and college.
 Concatenation:
o The + operator is used to concatenate member1 and member2
into a single tuple called concatenated_tuple.
 Printing:
o The concatenated tuple is printed to the console.

Output:

Concatenated tuple: ('Alice', 20, '123 Maple Street', 'University of Python',


'Bob', 22, '456 Oak Avenue', 'Python State College')

This program demonstrates how to create tuples, concatenate them, and


then print the resulting concatenated tuple in Python.

7(A).WRITE A PROGRAM TO COUNT THE NUMBERS OF VOWELS


IN A STRING ( NO CONTROL FLOW ALLOWED)

To count the number of vowels in a string without using control flow (such
as loops or conditionals), you can use a combination of Python's string
methods and functions like sum and map. Here's an example:

def count_vowels(input_string):

# Define the vowels

vowels = "aeiouAEIOU"

# Use sum() and map() to count the number of vowels in the input_string

vowel_count = sum(map(input_string.count, vowels))

return vowel_count

# Example usage

string = "Hello, World!"

vowel_count = count_vowels(string)
print(f"The number of vowels in the string is: {vowel_count}")

Explanation:

 Vowels: The string vowels contains all the vowels in both lowercase
and uppercase.
 Counting:
o The map() function applies the count() method for each vowel
in the vowels string.
o input_string.count(vowel) counts the occurrences of each vowel
in the input_string.
o sum() then adds up all these counts to give the total number of
vowels.

Output:

The number of vowels in the string is: 3

In this example, the string "Hello, World!" contains 3 vowels: e, o, and o.

8.WRITE A PROGRAM TO CHECK IF A GIVEN KEY EXISTS IN A


DICTIONARY OR NOT

Here's a Python program that checks if a given key exists in a dictionary:

# Define a dictionary

my_dict = {

"name": "Alice",

"age": 25,

"address": "123 Maple Street",

"college": "University of Python"

# Function to check if a key exists in the dictionary

def check_key_exists(dictionary, key):


return key in dictionary

# Example usage

key_to_check = "age"

if check_key_exists(my_dict, key_to_check):

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

Explanation:

 Dictionary:
o my_dict is a dictionary with some key-value pairs (e.g.,
"name": "Alice").
 Function:
o The check_key_exists() function takes two arguments: the
dictionary and the key to check.
o It uses the in operator to determine if the key exists in the
dictionary and returns True if it does, False otherwise.
 Example Usage:
o The key_to_check is set to "age", and the program checks if
this key exists in my_dict.
o Depending on whether the key is found, the program prints an
appropriate message.

Output:

The key 'age' exists in the dictionary.

This program efficiently checks if a specific key is present in a dictionary


using the in operator.

8(A).WRITE A PROGRAM TO ADD A NEW KEY VALUE PAIR TO AN


EXITING DICTIONARY
Here's a Python program that adds a new key-value pair to an existing
dictionary:

# Define an initial dictionary

my_dict = {

"name": "Alice",

"age": 25,

"address": "123 Maple Street"

# Function to add a new key-value pair to the dictionary

def add_key_value(dictionary, key, value):

dictionary[key] = value

# Example usage

new_key = "college"

new_value = "University of Python"

add_key_value(my_dict, new_key, new_value)

# Print the updated dictionary

print("Updated dictionary:", my_dict)

Explanation:

 Dictionary:
o my_dict is an initial dictionary containing some key-value
pairs.
 Function:
o The add_key_value() function takes three arguments:
dictionary, key, and value.
o It adds the new key-value pair to the dictionary using
dictionary[key] = value.
 Example Usage:
o The new_key is "college", and the new_value is "University of
Python".
o The program adds this key-value pair to my_dict.
 Output:
o The updated dictionary is printed, showing the newly added
key-value pair.

Output:

Updated dictionary: {'name': 'Alice', 'age': 25, 'address': '123 Maple


Street', 'college': 'University of Python'}

This program demonstrates how to add a new key-value pair to an existing


dictionary in Python.

9. WRITE A PROGRAM TO SUM ALL THE ITEMS IN A GIVEN


DICTIONARY

Here's a Python program that sums all the values in a given dictionary:

# Define a dictionary with numeric values

my_dict = {

"item1": 100,

"item2": 200,

"item3": 300,

"item4": 400

# Function to sum all the values in the dictionary

def sum_values(dictionary):
return sum(dictionary.values())

# Example usage

total_sum = sum_values(my_dict)

# Print the result

print("The sum of all the values in the dictionary is:", total_sum)

Explanation:

 Dictionary:
o my_dict is a dictionary with some items and their
corresponding numeric values.
 Function:
o The sum_values() function takes a dictionary as an argument.
o It uses the values() method to retrieve all the values from the
dictionary.
o The sum() function then calculates the sum of these values.
 Example Usage:
o The program calculates the sum of all the values in my_dict
and stores it in total_sum.
 Output:
o The result is printed, showing the total sum of the values in the
dictionary.

Output:

The sum of all the values in the dictionary is: 1000

This program efficiently sums all the numeric values in a dictionary using
Python's sum() function.

9(A).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
MUST BE LOWERED
Here's a Python program that reads words from an input file, converts
them to lowercase, sorts them, and writes the sorted words to an output
file:

# Function to read words from a file, sort them, and write to another file

def sort_words_in_file(input_file, output_file):

# Read words from the input file

with open(input_file, 'r') as infile:

# Read all the words, convert them to lowercase, and split into a list

words = infile.read().lower().split()

# Sort the list of words

sorted_words = sorted(words)

# Write the sorted words to the output file

with open(output_file, 'w') as outfile:

for word in sorted_words:

outfile.write(word + '\n')

# Example usage

input_file = 'input.txt'

output_file = 'output.txt'

sort_words_in_file(input_file, output_file)
print(f"Sorted words have been written to {output_file}.")

Explanation:

 Reading from Input File:


o Open the input_file in read mode ('r').
o Read the entire content of the file, convert it to lowercase with
.lower(), and split it into a list of words using .split().
 Sorting:
o The sorted() function sorts the list of words in ascending order.
 Writing to Output File:
o Open the output_file in write mode ('w').
o Write each sorted word to the file, followed by a newline
character ('\n').
 Example Usage:
o input_file is the name of the file containing the original words.
o output_file is the name of the file where the sorted, lowercase
words will be written.

Important Notes:

 Ensure that input.txt exists and contains the words you want to
process.
 The program will create or overwrite output.txt with the sorted list of
lowercase words.

Example Input (input.txt):

Banana Apple Orange apple BANANA

Example Output (output.txt):

apple

banana

orange

10.PYTHON PROGRAM TO PRINT EACH LINE OF A FILE IN


REVERSE ORDER

Here's a Python program that reads each line from a file and prints each
line in reverse order:
# Function to print each line of a file in reverse order

def print_lines_in_reverse(file_name):

# Open the file for reading

with open(file_name, 'r') as file:

# Read all lines from the file

lines = file.readlines()

# Process each line

for line in lines:

# Strip leading/trailing whitespace and reverse the line

reversed_line = line.strip()[::-1]

# Print the reversed line

print(reversed_line)

# Example usage

file_name = 'input.txt'

print_lines_in_reverse(file_name)

Explanation:

 Reading Lines:
o Open the file using with open(file_name, 'r') as file to ensure it
is properly closed after reading.
o Use file.readlines() to read all lines from the file into a list.
 Processing Lines:
o Iterate over each line in the list.
o Use line.strip() to remove any leading or trailing whitespace
(including newlines).
o Reverse the string using slicing [::-1].
o Print the reversed line.
 Example Usage:
o Set file_name to the name of the file you want to read.
o Call print_lines_in_reverse(file_name) to print each line of the
file in reverse order.

Example Input (input.txt):

Hello World

Python Programming

File Processing

Example Output:

dlroW olleH

gnimmargorP nohtyP

gnicorP eliF

This program effectively reads each line from a file, reverses the content of
each line, and prints the result. Make sure the input.txt file exists and
contains the text you want to process.

10.(A) PYTHON PROGRAM TO COMPUTE THE NUMBER OF


CHARACTERS,WORDS AND LINES IN A FILE

ere's a Python program that computes the number of characters, words,


and lines in a file:

def compute_file_stats(file_name):

# Initialize counters for characters, words, and lines

num_chars = 0

num_words = 0

num_lines = 0

# Open the file for reading

with open(file_name, 'r') as file:


# Process each line in the file

for line in file:

num_lines += 1

num_chars += len(line)

num_words += len(line.split())

return num_chars, num_words, num_lines

# Example usage

file_name = 'input.txt'

chars, words, lines = compute_file_stats(file_name)

# Print the results

print(f"Number of characters: {chars}")

print(f"Number of words: {words}")

print(f"Number of lines: {lines}")

Explanation:

 Initialization:
o num_chars, num_words, and num_lines are initialized to zero
to keep track of the count of characters, words, and lines
respectively.
 Reading the File:
o Open the file using with open(file_name, 'r') as file to ensure
the file is properly closed after reading.
o Iterate over each line in the file using a for loop.
 Counting:
o Lines: Increment num_lines for each line read.
o Characters: Use len(line) to count characters in the line and
add to num_chars.
o Words: Use line.split() to split the line into words and count
them using len(); add the count to num_words.
 Output:
o Print the results for characters, words, and lines.

Example Input (input.txt):

Hello World

Python Programming

File Processing

Example Output:

Number of characters: 52

Number of words: 6

Number of lines: 3

This program reads the file and computes the required statistics by
counting characters, words, and lines. Ensure that input.txt exists and
contains the text you want to analyze.

11.WRITE A PROGRAM TO CREATE DISPLAY ,APPEND,INSERT


AND REVERSE THE ORDER OF THE ITEMS IN THE ARRAY

Here's a Python program that demonstrates how to create an array (list),


display its contents, append new items, insert items at specific positions,
and reverse the order of the items:

# Define the initial array

my_array = [1, 2, 3, 4, 5]

# Function to display the array

def display_array(arr):

print("Current array:", arr)


# Function to append an item to the array

def append_item(arr, item):

arr.append(item)

print(f"Item {item} appended.")

# Function to insert an item at a specific index

def insert_item(arr, index, item):

if index < 0 or index > len(arr):

print("Invalid index.")

return

arr.insert(index, item)

print(f"Item {item} inserted at index {index}.")

# Function to reverse the order of items in the array

def reverse_array(arr):

arr.reverse()

print("Array reversed.")

# Example usage

display_array(my_array) # Display the initial array

append_item(my_array, 6) # Append item 6

display_array(my_array) # Display after appending


insert_item(my_array, 2, 99) # Insert item 99 at index 2

display_array(my_array) # Display after insertion

reverse_array(my_array) # Reverse the array

display_array(my_array) # Display after reversing

Explanation:

1. Initial Array:
o my_array is defined with initial values [1, 2, 3, 4, 5].
2. Display Function:
o display_array() prints the current contents of the array.
3. Append Function:
o append_item() appends a new item to the end of the array
using arr.append(item).
4. Insert Function:
o insert_item() inserts a new item at a specified index using
arr.insert(index, item).
o Checks if the index is valid before inserting.
5. Reverse Function:
o reverse_array() reverses the order of items in the array using
arr.reverse().
6. Example Usage:
o The program displays the array, appends an item, inserts an
item, and reverses the array, showing the results at each step.

Output:

Current array: [1, 2, 3, 4, 5]

Item 6 appended.

Current array: [1, 2, 3, 4, 5, 6]

Item 99 inserted at index 2.

Current array: [1, 2, 99, 3, 4, 5, 6]

Array reversed.

Current array: [6, 5, 4, 3, 99, 2, 1]


This program demonstrates how to work with arrays (lists) in Python by
performing basic operations such as appending, inserting, reversing, and
displaying the array.

11(A) WRITE A PROGRAM TO ADD TRANSPOSE AND MULTIPLY


TWO MATRICES

Here's a Python program to perform matrix operations, including addition,


transposition, and multiplication. For simplicity, we'll work with 2D lists
(matrices) and assume the matrices are compatible for the operations.

def add_matrices(matrix1, matrix2):

# Check if matrices have the same dimensions

if len(matrix1) != len(matrix2) or len(matrix1[0]) != len(matrix2[0]):

raise ValueError("Matrices must have the same dimensions for


addition.")

# Perform element-wise addition

result = [

[matrix1[i][j] + matrix2[i][j] for j in range(len(matrix1[0]))]

for i in range(len(matrix1))

return result

def transpose_matrix(matrix):

# Transpose the matrix

result = [

[matrix[j][i] for j in range(len(matrix))]

for i in range(len(matrix[0]))
]

return result

def multiply_matrices(matrix1, matrix2):

# Check if matrices can be multiplied (number of columns in matrix1


must be equal to number of rows in matrix2)

if len(matrix1[0]) != len(matrix2):

raise ValueError("Number of columns in matrix1 must be equal to


number of rows in matrix2.")

# Initialize result matrix with zeros

result = [[0] * len(matrix2[0]) for _ in range(len(matrix1))]

# Perform matrix multiplication

for i in range(len(matrix1)):

for j in range(len(matrix2[0])):

for k in range(len(matrix2)):

result[i][j] += matrix1[i][k] * matrix2[k][j]

return result

# Example usage

matrix1 = [

[1, 2],

[3, 4]
]

matrix2 = [

[5, 6],

[7, 8]

print("Matrix 1:")

for row in matrix1:

print(row)

print("\nMatrix 2:")

for row in matrix2:

print(row)

# Matrix Addition

print("\nMatrix Addition:")

try:

addition_result = add_matrices(matrix1, matrix2)

for row in addition_result:

print(row)

except ValueError as e:

print(e)
# Matrix Transposition

print("\nMatrix 1 Transposed:")

transpose_result1 = transpose_matrix(matrix1)

for row in transpose_result1:

print(row)

print("\nMatrix 2 Transposed:")

transpose_result2 = transpose_matrix(matrix2)

for row in transpose_result2:

print(row)

# Matrix Multiplication

print("\nMatrix Multiplication:")

try:

multiplication_result = multiply_matrices(matrix1, matrix2)

for row in multiplication_result:

print(row)

except ValueError as e:

print(e)

Explanation:

1. Matrix Addition:
o Checks if the dimensions of the matrices are the same.
o Adds corresponding elements of both matrices.
2. Matrix Transposition:
o Swaps rows and columns of the matrix.
3. Matrix Multiplication:
o Checks if the number of columns in the first matrix equals the
number of rows in the second matrix.
o Multiplies matrices using the dot product of rows and columns.

Output:

Matrix 1:

[1, 2]

[3, 4]

Matrix 2:

[5, 6]

[7, 8]

Matrix Addition:

[6, 8]

[10, 12]

Matrix 1 Transposed:

[1, 3]

[2, 4]

Matrix 2 Transposed:

[5, 7]

[6, 8]

Matrix Multiplication:
[19, 22]

[43, 50]

This program demonstrates how to perform basic matrix operations in


Python, including addition, transposition, and multiplication, using 2D
lists.

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

Here's a Python program that defines a base class Shape and three
subclasses Circle, Triangle, and Square. Each subclass implements
methods to calculate its area and perimeter.

import math

class Shape:

def area(self):

raise NotImplementedError("Subclasses should implement this


method.")

def perimeter(self):

raise NotImplementedError("Subclasses should implement this


method.")

class Circle(Shape):

def __init__(self, radius):

self.radius = radius
def area(self):

return math.pi * (self.radius ** 2)

def perimeter(self):

return 2 * math.pi * self.radius

class Triangle(Shape):

def __init__(self, a, b, c):

self.a = a

self.b = b

self.c = c

def area(self):

# Using Heron's formula to calculate area of the triangle

s = (self.a + self.b + self.c) / 2

return math.sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))

def perimeter(self):

return self.a + self.b + self.c

class Square(Shape):

def __init__(self, side):

self.side = side
def area(self):

return self.side ** 2

def perimeter(self):

return 4 * self.side

# Example usage

def print_shape_info(shape):

print(f"Area: {shape.area()}")

print(f"Perimeter: {shape.perimeter()}")

circle = Circle(radius=5)

triangle = Triangle(a=3, b=4, c=5)

square = Square(side=4)

print("Circle:")

print_shape_info(circle)

print("\nTriangle:")

print_shape_info(triangle)

print("\nSquare:")

print_shape_info(square)

Explanation:
1. Base Class Shape:
o Defines the abstract methods area() and perimeter(). These
methods are meant to be overridden by subclasses.
2. Subclass Circle:
o Initializes with a radius.
o Implements the area() method using the formula π×radius2\pi
\times \text{radius}^2π×radius2.
o Implements the perimeter() method using the formula
2×π×radius2 \times \pi \times \text{radius}2×π×radius.
3. Subclass Triangle:
o Initializes with the lengths of the three sides: a, b, and c.
o Implements the area() method using Heron's formula.
o Implements the perimeter() method by summing the sides.
4. Subclass Square:
o Initializes with the side length.
o Implements the area() method using the formula
side2\text{side}^2side2.
o Implements the perimeter() method using the formula 4×side4
\times \text{side}4×side.
5. Example Usage:
o Creates instances of Circle, Triangle, and Square.
o Uses the print_shape_info() function to print the area and
perimeter of each shape.

Output:

Circle:

Area: 78.53981633974483

Perimeter: 31.41592653589793

Triangle:

Area: 6.0

Perimeter: 12

Square:

Area: 16
Perimeter: 16

This program provides a clear example of how to use object-oriented


programming to represent different shapes and perform calculations
specific to each shape.

12(A).PYTHON PROGRAM TO CHECK WHETHER A JSON STRING


CONTAINS

To check whether a JSON string contains specific keys or values, you can
follow these steps:

1. Parse the JSON string into a Python dictionary.


2. Check for the presence of keys or values in the dictionary.

Here's a Python program that demonstrates how to check whether a JSON


string contains specific keys or values:

import json

def check_key_in_json(json_string, key):

try:

# Parse the JSON string into a Python dictionary

data = json.loads(json_string)

# Check if the key exists in the dictionary

if key in data:

return True

else:

return False

except json.JSONDecodeError:
print("Invalid JSON string.")

return False

def check_value_in_json(json_string, value):

try:

# Parse the JSON string into a Python dictionary

data = json.loads(json_string)

# Check if the value exists in the dictionary

for v in data.values():

if v == value:

return True

return False

except json.JSONDecodeError:

print("Invalid JSON string.")

return False

# Example JSON string

json_string = '{"name": "Alice", "age": 25, "city": "New York"}'

# Check for key

key_to_check = "age"

if check_key_in_json(json_string, key_to_check):

print(f"The key '{key_to_check}' exists in the JSON string.")


else:

print(f"The key '{key_to_check}' does not exist in the JSON string.")

# Check for value

value_to_check = "New York"

if check_value_in_json(json_string, value_to_check):

print(f"The value '{value_to_check}' exists in the JSON string.")

else:

print(f"The value '{value_to_check}' does not exist in the JSON string.")

Explanation:

1. check_key_in_json() Function:
o Parses the JSON string using json.loads() to convert it into a
Python dictionary.
o Checks if the specified key exists in the dictionary using the in
operator.
o Handles JSON decoding errors by catching
json.JSONDecodeError.
2. check_value_in_json() Function:
o Parses the JSON string into a Python dictionary.
o Iterates over the dictionary values to check if any value
matches the specified value.
o Handles JSON decoding errors similarly.
3. Example Usage:
o Defines a JSON string and checks for the presence of a specific
key and value using the provided functions.
o Prints results based on whether the key or value is found.

Output:

The key 'age' exists in the JSON string.

The value 'New York' exists in the JSON string.


This program demonstrates how to work with JSON strings in Python,
including parsing JSON and checking for the presence of specific keys or
values.

13.PYTHON PROGRAM TO DEMONSTRATE NUMPY ARRAYS


CREATION USING AARRAY () FUNCTIONS

To demonstrate NumPy arrays creation using the array() function from the
NumPy library, you need to first install the NumPy library if you haven't
already. You can install it using pip:

pip install numpy

Here’s a Python program that shows how to create NumPy arrays using
the array() function:

import numpy as np

# Create a 1D array

array_1d = np.array([1, 2, 3, 4, 5])

print("1D Array:")

print(array_1d)

# Create a 2D array

array_2d = np.array([[1, 2, 3], [4, 5, 6]])

print("\n2D Array:")

print(array_2d)

# Create a 3D array

array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

print("\n3D Array:")
print(array_3d)

# Create an array with a specific data type

array_float = np.array([1, 2, 3, 4, 5], dtype=float)

print("\nArray with Float Data Type:")

print(array_float)

# Create an array with a specific shape using nested lists

array_shape = np.array([[1, 2], [3, 4], [5, 6]])

print("\nArray with Specific Shape:")

print(array_shape)

# Create an empty array (uninitialized)

empty_array = np.array([[None]*3]*3)

print("\nEmpty Array (Uninitialized):")

print(empty_array)

Explanation:

1. Import NumPy:
o import numpy as np imports the NumPy library and gives it an
alias np.
2. 1D Array:
o array_1d = np.array([1, 2, 3, 4, 5]) creates a one-dimensional
array.
3. 2D Array:
o array_2d = np.array([[1, 2, 3], [4, 5, 6]]) creates a two-
dimensional array (matrix).
4. 3D Array:
o array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) creates a
three-dimensional array (tensor).
5. Array with Specific Data Type:
o array_float = np.array([1, 2, 3, 4, 5], dtype=float) creates an
array with a specified data type (float).
6. Array with Specific Shape Using Nested Lists:
o array_shape = np.array([[1, 2], [3, 4], [5, 6]]) creates an array
with a specific shape.
7. Empty Array (Uninitialized):
o empty_array = np.array([[None]*3]*3) creates an empty array
filled with None values. Note that this creates an array of
objects, and it's generally used for demonstration.

Output:

1D Array:

[1 2 3 4 5]

2D Array:

[[1 2 3]

[4 5 6]]

3D Array:

[[[1 2]

[3 4]]

[[5 6]

[7 8]]]

Array with Float Data Type:

[1. 2. 3. 4. 5.]
Array with Specific Shape:

[[1 2]

[3 4]

[5 6]]

Empty Array (Uninitialized):

[[None None None]

[None None None]

[None None None]]

This program covers the basic use of the np.array() function to create
arrays of different dimensions, data types, and shapes using NumPy.

13(A).PYTHON PROGRAM TO DEMONSTRATE USE OF


NDIM,SHAPE,SIZE,DTYPE

Here's a Python program that demonstrates the use of NumPy attributes:


ndim, shape, size, and dtype. These attributes provide information about
the dimensions, shape, total number of elements, and data type of a NumPy
array, respectively.

import numpy as np

# Create a sample NumPy array

array = np.array([[1, 2, 3], [4, 5, 6]])

# Display the array

print("Array:")

print(array)
# Number of dimensions (ndim)

print("\nNumber of dimensions (ndim):", array.ndim)

# Shape of the array (shape)

print("Shape of the array (shape):", array.shape)

# Total number of elements (size)

print("Total number of elements (size):", array.size)

# Data type of the elements (dtype)

print("Data type of the elements (dtype):", array.dtype)

Explanation:

1. Import NumPy:
o import numpy as np imports the NumPy library.
2. Create a Sample NumPy Array:
o array = np.array([[1, 2, 3], [4, 5, 6]]) creates a 2D NumPy array
with shape (2, 3).
3. Number of Dimensions (ndim):
o array.ndim returns the number of dimensions of the array. For
a 2D array, it returns 2.
4. Shape of the Array (shape):
o array.shape returns a tuple representing the shape of the
array. For a 2D array with 2 rows and 3 columns, it returns (2,
3).
5. Total Number of Elements (size):
o array.size returns the total number of elements in the array.
For a 2D array with 2 rows and 3 columns, it returns 6.
6. Data Type of the Elements (dtype):
o array.dtype returns the data type of the elements in the array.
For integers, it typically returns int64 or int32, depending on
the platform.
Output:

Array:

[[1 2 3]

[4 5 6]]

Number of dimensions (ndim): 2

Shape of the array (shape): (2, 3)

Total number of elements (size): 6

Data type of the elements (dtype): int64

This program covers how to retrieve and display information about a


NumPy array's dimensions, shape, size, and data type using the ndim,
shape, size, and dtype attributes.

14.python program to demonstrate basic slicing,integer and Boolean


indexing

Here's a Python program that demonstrates basic slicing, integer indexing,


and Boolean indexing using NumPy arrays.

import numpy as np

# Create a sample NumPy array

array = np.array([[10, 20, 30, 40],

[50, 60, 70, 80],

[90, 100, 110, 120]])

print("Original Array:")

print(array)
# Basic Slicing

# Slice the first two rows and the first three columns

sliced_array = array[:2, :3]

print("\nBasic Slicing (first 2 rows and first 3 columns):")

print(sliced_array)

# Integer Indexing

# Select specific elements using integer indexing

integer_indexed_array = array[[0, 1, 2], [1, 2, 3]] # Elements at positions


(0,1), (1,2), (2,3)

print("\nInteger Indexing (elements at positions (0,1), (1,2), (2,3)):")

print(integer_indexed_array)

# Boolean Indexing

# Create a boolean array where the condition is met

boolean_index = array > 60

print("\nBoolean Indexing (values greater than 60):")

print(boolean_index)

print("Filtered Array (values greater than 60):")

print(array[boolean_index])

import numpy as np

# Create a sample NumPy array

array = np.array([[10, 20, 30, 40],


[50, 60, 70, 80],

[90, 100, 110, 120]])

print("Original Array:")

print(array)

# Basic Slicing

# Slice the first two rows and the first three columns

sliced_array = array[:2, :3]

print("\nBasic Slicing (first 2 rows and first 3 columns):")

print(sliced_array)

# Integer Indexing

# Select specific elements using integer indexing

integer_indexed_array = array[[0, 1, 2], [1, 2, 3]] # Elements at positions


(0,1), (1,2), (2,3)

print("\nInteger Indexing (elements at positions (0,1), (1,2), (2,3)):")

print(integer_indexed_array)

# Boolean Indexing

# Create a boolean array where the condition is met

boolean_index = array > 60

print("\nBoolean Indexing (values greater than 60):")

print(boolean_index)

print("Filtered Array (values greater than 60):")


print(array[boolean_index])

Explanation:

1. Import NumPy:
o import numpy as np imports the NumPy library.
2. Create a Sample NumPy Array:
o array is a 3x4 NumPy array created with some sample values.
3. Basic Slicing:
o sliced_array = array[:2, :3] slices the array to get the first 2
rows and the first 3 columns. The result is a 2x3 sub-array.
4. Integer Indexing:
o integer_indexed_array = array[[0, 1, 2], [1, 2, 3]] selects
elements from specific positions in the array. Here, it selects
elements from positions (0,1), (1,2), and (2,3).
5. Boolean Indexing:
o boolean_index = array > 60 creates a boolean array where each
element is True if the corresponding element in array is greater
than 60.
o array[boolean_index] filters the original array to include only
elements where the condition is True.

Output:

Original Array:

[[ 10 20 30 40]

[ 50 60 70 80]

[ 90 100 110 120]]

Basic Slicing (first 2 rows and first 3 columns):

[[10 20 30]

[50 60 70]]

Integer Indexing (elements at positions (0,1), (1,2), (2,3)):

[ 20 70 120]
Boolean Indexing (values greater than 60):

[[False False False False]

[False False True True]

[ True True True True]]

Filtered Array (values greater than 60):

[ 70 80 90 100 110 120]

This program demonstrates basic slicing to extract sub-arrays, integer


indexing to select specific elements, and Boolean indexing to filter elements
based on a condition using NumPy arrays.

14(A) PYTHON PROGRAM TO FIND MIN,MAX,SUM,CUMULATIVE


SUM OF ARRAY

Here's a Python program using NumPy to find the minimum, maximum,


sum, and cumulative sum of elements in a NumPy array.

import numpy as np

# Create a sample NumPy array

array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

print("Array:")

print(array)

# Find the minimum value

min_value = np.min(array)

print("\nMinimum value in the array:")


print(min_value)

# Find the maximum value

max_value = np.max(array)

print("\nMaximum value in the array:")

print(max_value)

# Find the sum of all elements

sum_value = np.sum(array)

print("\nSum of all elements in the array:")

print(sum_value)

# Find the cumulative sum

cumulative_sum = np.cumsum(array)

print("\nCumulative sum of the array:")

print(cumulative_sum)

xplanation:

1. Import NumPy:
o import numpy as np imports the NumPy library.
2. Create a Sample NumPy Array:
o array is a 1D NumPy array with values from 1 to 10.
3. Find the Minimum Value:
o np.min(array) returns the smallest value in the array.
4. Find the Maximum Value:
o np.max(array) returns the largest value in the array.
5. Find the Sum of All Elements:
o np.sum(array) returns the sum of all elements in the array.
6. Find the Cumulative Sum:
o np.cumsum(array) returns an array where each element is the
sum of the elements up to that position.

Output:

Array:

[ 1 2 3 4 5 6 7 8 9 10]

Minimum value in the array:

Maximum value in the array:

10

Sum of all elements in the array:

55

Cumulative sum of the array:

[ 1 3 6 10 15 21 28 36 45 55]

This program demonstrates how to use NumPy functions to perform


common statistical operations on arrays, including finding minimum and
maximum values, computing the sum of elements, and calculating the
cumulative sum.

15.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 ()
Here's a Python program that demonstrates how to create a dictionary
with lists as values, convert it to a Pandas DataFrame, and explore the data
using the head() method.

import pandas as pd

# Create a dictionary with lists as values

data = {

'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva', 'Frank', 'Grace',


'Hannah', 'Isaac', 'Jack'],

'Age': [24, 27, 22, 32, 29, 31, 25, 28, 26, 30],

'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix',


'Philadelphia', 'San Antonio', 'San Diego', 'Dallas', 'San Jose'],

'Occupation': ['Engineer', 'Doctor', 'Artist', 'Lawyer', 'Chef', 'Teacher',


'Nurse', 'Designer', 'Photographer', 'Journalist'],

'Salary': [70000, 80000, 65000, 90000, 55000, 60000, 62000, 67000, 71000,
69000]

# Convert the dictionary to a Pandas DataFrame

df = pd.DataFrame(data)

# Display the first few rows of the DataFrame using head()

print("DataFrame with the first few rows:")

print(df.head())

Explanation:

1. Import Pandas:
o import pandas as pd imports the Pandas library.
2. Create a Dictionary:
o data is a dictionary where each key corresponds to a list of
values. Each list contains 10 values.
3. Convert Dictionary to DataFrame:
o df = pd.DataFrame(data) converts the dictionary to a Pandas
DataFrame.
4. Apply head() Method:
o df.head() displays the first five rows of the DataFrame.

Output:

Data Frame with the first few rows:

Name Age City Occupation Salary

0 Alice 24 New York Engineer 70000

1 Bob 27 Los Angeles Doctor 80000

2 Charlie 22 Chicago Artist 65000

3 David 32 Houston Lawyer 90000

4 Eva 29 Phoenix Chef 55000

This program demonstrates how to create a dictionary with lists, convert it


into a Pandas DataFrame, and use the head() method to preview the first
few rows of the DataFrame.

You might also like