0% found this document useful (0 votes)
58 views50 pages

Python Mannual

The program shows how to create and raise user-defined exceptions in Python. It defines a NotPrimeError exception class and checks if a given number is prime or not. If not prime, the exception is raised after printing the message that the number is not prime.

Uploaded by

rasalshweta221
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)
58 views50 pages

Python Mannual

The program shows how to create and raise user-defined exceptions in Python. It defines a NotPrimeError exception class and checks if a given number is prime or not. If not prime, the exception is raised after printing the message that the number is not prime.

Uploaded by

rasalshweta221
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
You are on page 1/ 50

1. Write a program to capitalize first and last letter of given string?

Program:

def capitalize_first_and_last(string):
if len(string) < 2:
return string

first_letter = string[0].upper()
last_letter = string[-1].upper()
middle_letters = string[1:-1]
return first_letter + middle_letters + last_letter
# Example usage
input_string = input("Enter a string: ")
result = capitalize_first_and_last(input_string)
print("Result:", result)

Output:
2. Write a python program for the following.
i) Create list of fruits
ii) Add new fruit in list.
iii) Sort the list.
iv) Delete last fruit name from list

Program:

Fruits=['Apple','Banana','Orange']

print(Fruits)

Fruits.append('Mango')

print('Added new fruit name in list:',Fruits)

Fruits.sort()

print('Sorted list of fruits:',Fruits)

Fruits.pop()

print('Deleted last element of list:', Fruits)

Output:
3. Write a program for tuple &set operations?

Program:

Tuple:

tuple1=(1,2,3,4,5)

tuple2=(6,7,8)

tuple3=(9,0)

# Accessing tuple elements

print('Print tuple 1:', tuple1)

print('print tuple 1, third element:', tuple1[2])

# Concatenating tuples

tuple_concat=tuple1+tuple2

print('concated tuple:',tuple_concat)

# Checking if an element exists in a tuple print("Is 3 in Tuple 1?", 3 in tuple1)

print("Is 10 in Tuple 2?", 10 in tuple2)

# Length of a tuple

print("Length of Tuple 3:", len(tuple3))

# Converting tuple to a set set_from_tuple = set(tuple1)

set_from_tuple=set(tuple1)

print("Set from Tuple 1:", set_from_tuple)

Output:
Sets:

# Creating sets

set1 = {1, 2, 3, 4, 5}

set2 = {4, 5, 6, 7}

set3 = {5, 6, 7, 8, 9}

# Accessing set elements print("Set 1:", set1)

# Adding elements to a set set1.add(6)

print("Set 1 after adding element 6:", set1)

# Removing elements from a set set1.remove(3)

print("Set 1 after removing element 3:", set1)

# Set union

set_union = set1.union(set2)

print("Union of Set 1 and Set 2:", set_union)

# Set intersection

set_intersection = set1.intersection(set2)

print("Intersection of Set 1 and Set 2:", set_intersection)

# Set difference

set_difference = set1.difference(set2)

print("Difference of Set 1 and Set 2:", set_difference)

# Set symmetric difference

set_sym_difference = set1.symmetric_difference(set2)

print("Symmetric Difference of Set 1 and Set 2:", set_sym_difference)

# Checking if a set is a subset of another set

print("Is Set 3 a subset of Set 1?", set3.issubset(set1))

# Checking if a set is a superset of another set

print("Is Set 1 a superset of Set 2?", set1.issuperset(set2))


Output:
4. Write a program to demonstrate dictionary operations to import module using from
Keyword.

Program:

# Importing module using 'from' keyword

from math import sqrt

# Dictionary operations

student = {

'name': 'John', 'age': 20,

'grade': 'A'}

# Accessing dictionary elements

print("Student name:", student['name'])

print("Student age:", student['age'])

print("Student grade:", student['grade'])

# Modifying dictionary elements

student['age'] = 21

student['grade'] = 'B'

print("Updated student age:", student['age'])

print("Updated student grade:", student['grade'])

# Adding new elements to the dictionary

student['address'] = '123 Main Street'

print("Student address:", student['address'])

# Removing elements from the dictionary

del student['grade']

print("Student dictionary after deleting grade:", student)

# Using the imported module

number = 16

square_root = sqrt(number)

print("Square root of", number, "is", square_root)


Output:
5. Write a program to create User defined package,subpackage mypack?

Program:

import os

main_dir = "C:/mypack"

os.mkdir(main_dir)

print("Directory '% s' is built!" % main_dir)

#we created subpack in Practice

import os

main_dir = "C:/Practice/subpackage"

os.mkdir(main_dir)

print("sub-Directory '% s' is built!" % main_dir)

Output:
6. Write a program Reading and Writing file?

Program:

# Reading and Writing file

# File path

file_path = "example.txt"

# Open the file for writing

with open(file_path, "w") as file:

# Write data to the file

file.write("Hello, World!\n")

file.write("This is an example file.\n")

file.write("Writing some data to it.\n")

# Open the file for reading

with open(file_path, "r") as file:

# Read and print the contents of the file

content = file.read()

print("File Contents:")

print(content)

Output:
7. Write a program Reading and Writing into Binary file?

Program:

# Reading and Writing into Binary file

# File path

file_path = "example.bin"

# Data to write to the binary file

data_to_write = b"Hello, Binary World!\nThis is an example binary file."

# Open the file for writing in binary mode

with open(file_path, "wb") as file:

# Write binary data to the file

file.write(data_to_write)

# Open the file for reading in binary mode

with open(file_path, "rb") as file:

# Read and print the contents of the binary file

content = file.read()

print("File Contents:")

print(content)
Output:
8. Write a program to create text file?

Program:

# Creating a Text File

# File path

file_path = "filecreate.txt"

# Content to write to the file

content = """Hello, World!

This is an example text file.

Creating a text file using Python."""

# Open the file for writing

with open(file_path, "w") as file:

# Write the content to the file

file.write(content)

print("File created successfully!")

Output:
9. Write a python code to diplay first m and last n lines from text file?

Program:

def display_first_and_last_lines(file_path, m, n):

with open(file_path, "r") as file:

lines = file.readlines()

# Display first m lines

print(f"First {m} lines:")

for line in lines[:m]:

print(line.strip())

# Display last n lines

print(f"\nLast {n} lines:")

for line in lines[-n:]:

print(line.strip())

# File path

file_path = "example.txt" # Replace with the path to your text file

# Specify the number of lines to display

m = 5 # Number of first lines to display

n = 5 # Number of last lines to display

# Call the function to display the first m and last n lines

display_first_and_last_lines(file_path, m, n)
Output:
10. Write a program to create user defined exception not prime if given number is not prime else
print the prime number?

Program:

class NotPrimeError(Exception):

pass

def is_prime(number):

if number < 2:

return False

for i in range(2, int(number ** 0.5) + 1):

if number % i == 0:

return False

return True

try:

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

if is_prime(number):

print(f"{number} is a prime number.")

else:

raise NotPrimeError(f"{number} is not a prime number.")

except ValueError:

print("Invalid input. Please enter a valid number.")

except NotPrimeError as e:

print(e)

Output:
11. Write a program to replace the last three characters of string with ‘ing’,if having’ing’ inthe string
then replace by ‘ly’?
Program:

def replace_last_three_chars(string):

if string.endswith("ing"):

return string[:-3] + "ly"

else:

return string[:-3] + "ing"

# Prompt the user to enter a string

string = input("Enter a string: ")

# Call the function to replace the last three characters

result = replace_last_three_chars(string)

# Print the modified string

print("Modified string:", result)

Output:
12. Write a program that accept the string from user and display the same string after removing
vowels from it?

Program:

def remove_vowels(string):

vowels = ['a', 'e', 'i', 'o', 'u']

result = ""

for char in string:

if char.lower() not in vowels:

result += char

return result

# Prompt the user to enter a string

string = input("Enter a string: ")

# Call the function to remove vowels

result = remove_vowels(string)

# Print the modified string

print("Modified string:", result)

Output:
13. Create class called, library with data attributes like Acc-number publisher, title and author,
the methods of the class should include- i) Read ( ) - Acc- number, title, author,publisher. ii)
Compute ( ) - to accept the number of day late, calculate and display the fine charged at the
rate of Rupees 5/- per day. iii) Display the data?
Program:

class Library:

def __init__(self, acc_number, publisher, title, author):

self.acc_number = acc_number

self.publisher = publisher

self.title = title

self.author = author

def read(self):

print("Acc Number:", self.acc_number)

print("Title:", self.title)

print("Author:", self.author)

print("Publisher:", self.publisher)

def compute(self, days_late):

fine = days_late * 5

print("Fine charged: Rs.", fine)

def display(self):

print("Acc Number:", self.acc_number)

print("Title:", self.title)

print("Author:", self.author)

print("Publisher:", self.publisher)

# Example usage:

book1 = Library(123456, "ABC Publications", "Python


Programming", "John Doe")

print("Reading Book Information:")

book1.read()

print("\nComputing Fine for Late Return (10 days late):")

book1.compute(10)

print("\nDisplaying Book Information:")

book1.display()
Output:
14. Develop a program to print the number of lines, words and characters present in the given file?
Accept the file name from user. Handle necessary exceptions?

Program:

def count_lines_words_chars(file_name):

try:

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

lines = 0

words = 0

characters = 0

for line in file:

lines += 1

words += len(line.split())

characters += len(line)

print("Number of lines:", lines)

print("Number of words:", words)

print("Number of characters:", characters)

except FileNotFoundError:

print("Error: File not found.")

except PermissionError:

print("Error: Permission denied.")

# Get file name from user

file_name = input("Enter the file name: ")

# Call the function

count_lines_words_chars(file_name)

Output:
15. Write a program to guess correct no that is 10 and throw user defined exceptionToosmallnumber if number is
small and throw exception Toolargenumber if enterednumber is large?

Program:

class TooSmallNumber(Exception):

pass

class TooLargeNumber(Exception):

pass

def guess_number(guess):

target_number = 10

if guess < target_number:

raise TooSmallNumber("Guessed number is too small!")

elif guess > target_number:

raise TooLargeNumber("Guessed number is too large!")

else:

print("Congratulations! You guessed the correct number!")

try:

user_guess = int(input("Enter your guess: "))

guess_number(user_guess)

except TooSmallNumber as e:

print(e)

except TooLargeNumber as e:

print(e)

Output:
16. Write a program to demonstrate class and object to create employee class?

Program:

class Employee:

def __init__(self, emp_id, name, salary):

self.emp_id = emp_id

self.name = name

self.salary = salary

def display(self):

print("Employee ID:", self.emp_id)

print("Name:", self.name)

print("Salary:", self.salary)

# Creating objects of Employee class

emp1 = Employee(101, "John Doe", 50000)

emp2 = Employee(102, "Jane Smith", 60000)

# Displaying information of employees

print("Employee 1 Information:")

emp1.display()

print("\nEmployee 2 Information:")

emp2.display()

Output:
17. Write a python program to implement student class which has method to calculate percentage.
Assume suitable class variable?

Program:

class Student:

total_students = 0 # Class variable to keep track of total students

def __init__(self, name, roll_number, marks):

self.name = name

self.roll_number = roll_number

self.marks = marks

Student.total_students += 1

def calculate_percentage(self):

total_marks = sum(self.marks)

percentage = (total_marks / (len(self.marks) * 100)) * 100

return percentage

@classmethod

def display_total_students(cls):

print("Total Students:", cls.total_students)

# Example usage:

student1 = Student("John", 101, [85, 90, 75, 80, 95])

student2 = Student("Jane", 102, [75, 80, 70, 85, 90])

# Calculate and display percentage of students

print("Student 1 Percentage:", student1.calculate_percentage(), "%")

print("Student 2 Percentage:", student2.calculate_percentage(), "%")

# Display total number of students

Student.display_total_students()

Output:
18. Write a program for python constructor and destructor?

Program:

class MyClass:

def __init__(self, name):

self.name = name

print(f"Constructor called. Object '{self.name}' created.")

def __del__(self):

print(f"Destructor called. Object '{self.name}' destroyed.")

# Creating objects of MyClass

obj1 = MyClass("Object 1")

obj2 = MyClass("Object 2")

# Deleting objects

del obj1

del obj2

Output:
19. Write a python code to demonstrate multiple and multilevel inheritance?

Program:

class Animal:

def __init__(self, name):

self.name = name

def speak(self):

pass

class Mammal(Animal):

def __init__(self, name):

super().__init__(name)

def give_birth(self):

print(f"{self.name} is giving birth...")

class Dog(Mammal):

def __init__(self, name):

super().__init__(name)

def speak(self):

return "Woof!"

class Cat(Mammal):

def __init__(self, name):

super().__init__(name)

def speak(self):

return "Meow!"

class Bird(Animal):

def __init__(self, name):

super().__init__(name)

def fly(self):

print(f"{self.name} is flying...")

class Parrot(Bird):

def __init__(self, name):

super().__init__(name)

def speak(self):

return "Squawk!"

if __name__ == "__main__":

dog = Dog("Buddy")
if __name__ == "__main__":

dog = Dog("Buddy")

print(dog.speak())

dog.give_birth()

cat = Cat("Whiskers")

print(cat.speak())

cat.give_birth()

parrot = Parrot("Polly")

print(parrot.speak())

parrot.fly()

Output:
20. Write a program to demonstrate class variable, data hiding, method overriding andoperator overloading?

Program: class Counter:

__count = 0 # private class variable

def __init__(self):

Counter.__count += 1 # increment count when an object is created

def get_count(self):

return Counter.__count

def __str__(self):

return f"Counter: {Counter.__count}"

def __add__(self, other): # operator overloading

return Counter.__count + other.get_count()

class SpecialCounter(Counter):

__count = 100 # hiding the parent's class variable

def get_count(self): # method overriding

return SpecialCounter.__count

def __str__(self):

return f"Special Counter: {SpecialCounter.__count}"

# Demo

print("Creating Counters:")

c1 = Counter()

c2 = Counter()

print(c1) # Output: Counter: 2

print("\nCreating Special Counters:")

sc1 = SpecialCounter()

sc2 = SpecialCounter()

print(sc1) # Output: Special Counter: 100

print("\nUsing method overriding:")

print("Count from Counter:", c1.get_count()) # Output: Count from Counter: 4

print("Count from Special Counter:", sc1.get_count()) # Output: Count from


Special Counter: 100

print("\nUsing operator overloading:")

total_count = c1 + sc1

print("Total count:", total_count) # Output: Total count: 102


Output:
21. Write a program to validate email address and mobile number using regular expression?

Program:
import re

def validate_email(email):

# Regular expression for email validation

pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'

if re.match(pattern, email):

return True

else:

return False

def validate_mobile_number(number):

# Regular expression for mobile number validation

pattern = r'^\d{10}$'

if re.match(pattern, number):

return True

else:

return False

# Test the functions

email = "[email protected]"

mobile_number = "1234567890"

if validate_email(email):

print("Email is valid")

else:

print("Email is invalid")

if validate_mobile_number(mobile_number):

print("Mobile number is valid")

else:

print("Mobile number is invalid")


Output:
22. Write a program to search string using given pattern and replace that string by yourfirst
name using regular expression?

Program:

import re

def replace_with_name(pattern, text, replacement):

# Compile the regular expression pattern

regex = re.compile(pattern)

# Replace the matched pattern with the replacement string

result = re.sub(regex, replacement, text)

return result

# Example usage

pattern = r'\b[A-Z][a-z]+\b' # Pattern to match capitalized words

text = "Hello, World! My name is John. Nice to meet you, John."

replacement = "Alice" # Your first name

result = replace_with_name(pattern, text, replacement)

print("Original text:", text)

print("Modified text:", result)

Output:
23. Write a program to search name and age from given data?

Program:

class Data:

def __init__(self):

# Sample data (name and age pairs)

self.data = {

"John": 25,

"Jane": 30,

"Alice": 22,

"Bob": 28,

"Emma": 35

def search(self, name):

if name in self.data:

return name, self.data[name]

else:

return None, None

# Example usage:
Output:
data_obj = Data()

# Searching for name and age

search_name = "Alice"

name, age = data_obj.search(search_name)

if name is not None:

print(f"Name: {name}, Age: {age}")

else:

print(f"Name '{search_name}' not found in the data.")


24. Write a program to create iterator using regular expression?

Program:

import re

def regex_iterator(pattern, string):

"""

Function to create an iterator using regular expressions.

Args:

pattern (str): The regular expression pattern to search for.

string (str): The input string to search within.

Returns:

iterator: Iterator yielding match objects.

"""

return re.finditer(pattern, string)

# Example usage:

pattern = r'\d+' # Regular expression pattern to match digits

string = 'I have 10 apples and 5 oranges.'

# Create the iterator

iterator = regex_iterator(pattern, string)

# Iterate over matches

for match in iterator:

print(match.group()) # Output the matched string

Output:
25. Write a program for addition of matrix and transpose of matrix using list
comprehension?

Program:

def transpose(matrix):

“”” Function to transpose a matrix using list comprehension.

Args:

matrix (list of lists): The input matrix.

Returns:

list of lists: Transposed matrix.

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


range(len(matrix[0]))]

def matrix_addition(matrix1, matrix2):

Function to add two matrices using list comprehension.

Args:

matrix1 (list of lists): The first matrix.

matrix2 (list of lists): The second matrix.

Returns:

list of lists: Resultant matrix after addition.

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

raise ValueError("Matrices must have the same dimensions for


addition.")

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


in range(len(matrix1))]”””

# Example matrices

matrix1 = [[1, 2, 3],

[4, 5, 6],

[7, 8, 9]]

matrix2 = [[9, 8, 7],

[6, 5, 4],

[3, 2, 1]]

# Add matrices

result_addition = matrix_addition(matrix1, matrix2)

# Transpose matrices

transposed_matrix1 = transpose(matrix1)

transposed_matrix2 = transpose(matrix2)
# Transpose matrices

transposed_matrix1 = transpose(matrix1)

transposed_matrix2 = transpose(matrix2)

# Output results

print("Matrix 1:")

for row in matrix1:

print(row)

print("\nMatrix 2:")

for row in matrix2:

print(row)

print("\nResultant Matrix after addition:")

for row in result_addition:

print(row)

print("\nTransposed Matrix 1:")

for row in transposed_matrix1:

print(row)

print("\nTransposed Matrix 2:")

for row in transposed_matrix2:

print(row)

Output:
26. Write a program to plot a line chart?

Program:

import matplotlib.pyplot as plt


# Data for the x-axis (time or any other independent
variable)x_values = [1, 2, 3, 4, 5]
# Data for the y-axis (dependent
variable)y_values = [3, 5, 2, 7, 4]
# Plotting the line chart
plt.plot(x_values, y_values,
marker='o')
#Addig labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Chart
Example')

# Displaying
the chart
plt.show()

Output:
27. Write a program to check whether entered string & number is palindrome or not?

Program:

def is_palindrome(input_str):

“””Function to check whether a string or number is a palindrome.

Args:

input_str (str or int): The input string or number.

Returns:

bool: True if the input is a palindrome, False otherwise.”””

# Convert the input to a string for uniform handling

input_str = str(input_str)

# Check if the string is equal to its reverse

return input_str == input_str[::-1]

# Function to take user input and check for palindrome

def main():

user_input = input("Enter a string or number: ")

if is_palindrome(user_input):

print("Yes, it's a palindrome.")

else:

print("No, it's not a palindrome.")

if __name__ == "__main__":

main()

Output:
28. Illustrate CRUD operations in MongoDB with example?

Program:

import pymongo

# Connect to MongoDB

client = pymongo.MongoClient("mongodb://localhost:27017/")

# Create a database (if not exists)

mydb = client["mydatabase"]

# Create a collection (similar to a table in SQL)

mycol = mydb["customers"]

# Insert one document

customer_data = {"name": "John", "email": "[email protected]"}

inserted_doc = mycol.insert_one(customer_data)

print("Inserted document ID:", inserted_doc.inserted_id)

# Insert multiple documents

customer_data_list = [{"name": "Alice", "email": "[email protected]"},

{"name": "Bob", "email": "[email protected]"}]

inserted_docs = mycol.insert_many(customer_data_list)

print("Inserted documents IDs:", inserted_docs.inserted_ids)

# Find one document

print("One document:")

print(mycol.find_one())

# Find all documents

print("\nAll documents:")

for document in mycol.find():

print(document)

# Find documents with a specific condition

print("\nDocuments with name 'John':")

query = {"name": "John"}

for document in mycol.find(query):

print(document)

# Update one document

query = {"name": "John"}

new_values = {"$set": {"email": "[email protected]"}}


# Update one document

query = {"name": "John"}

new_values = {"$set": {"email": "[email protected]"}}

mycol.update_one(query, new_values)

# Update multiple documents

query = {"name": {"$regex": "^A"}} # starts with 'A'

new_values = {"$set": {"status": "active"}}

updated_docs = mycol.update_many(query, new_values)

print("Number of documents updated:", updated_docs.modified_count)

# Delete one document

query = {"name": "Alice"}

mycol.delete_one(query)

# Delete multiple documents

query = {"name": {"$regex": "^B"}} # starts with 'B'

deleted_docs = mycol.delete_many(query)

print("Number of documents deleted:", deleted_docs.deleted_count)

# Delete all documents in a collection

deleted_all_docs = mycol.delete_many({})

print("Number of documents deleted:", deleted_all_docs.deleted_count)

Output:
29. Write a pythan program to perform following operations. on MongoDB Database-
a. Create collection “EMP” with fields: Emp-name, Emp- mobile, Emp, sal, Age
b. Insert 5 documents.
c. Find the employees getting salary between 5000 to 10000.
d. Update mobile number for the employee named as “Riddhi”
e. Display all empolyees in the order of ”Age”
Program: import pymongo

# Connect to MongoDB (assuming MongoDB is running locally on default port


27017)

client = pymongo.MongoClient("mongodb://localhost:27017/")

# Create or access the database

mydb = client["mydatabase"]

# i) Create collection "EMP" with fields: Emp-name, Emp-mobile, Emp-sal,


Age

emp_collection = mydb["EMP"]

# ii) Insert 5 documents

employees = [

{"Emp-name": "John", "Emp-mobile": "1234567890", "Emp-sal": 8000,


"Age": 30},

{"Emp-name": "Alice", "Emp-mobile": "9876543210", "Emp-sal": 6000,


"Age": 25},

{"Emp-name": "Bob", "Emp-mobile": "1112223334", "Emp-sal": 7000,


"Age": 35},

{"Emp-name": "Riddhi", "Emp-mobile": "5556667778", "Emp-sal": 9000,


"Age": 28},

{"Emp-name": "Sara", "Emp-mobile": "9998887776", "Emp-sal": 8500,


"Age": 32}]

emp_collection.insert_many(employees)

# iii) Find the employees getting salary between 5000 to 10000

query = {"Emp-sal": {"$gte": 5000, "$lte": 10000}}

print("Employees getting salary between 5000 to 10000:")

for employee in emp_collection.find(query):

print(employee)

# iv) Update mobile number for the employee named as "Riddhi"

query = {"Emp-name": "Riddhi"}

new_values = {"$set": {"Emp-mobile": "7778889990"}}

emp_collection.update_one(query, new_values)
# v) Display all employees in the order of "Age"

print("\nEmployees sorted by Age:")

for employee in emp_collection.find().sort("Age"):

print(employee)

Output:
30. Write a pythan program to find the factorial of a given number using recursion?

Program:

def factorial(n):

“””Function to calculate the factorial of a given number


using recursion.

Args:

n (int): The number whose factorial needs to be calculated.

Returns:

int: The factorial of the given number.”””

# Base case: factorial of 0 or 1 is 1

if n == 0 or n == 1:

return 1

# Recursive case: factorial of n is n * factorial(n-1)

else:

return n * factorial(n - 1)

# Input from user

num = int(input("Enter a number to find its factorial: "))

# Call the factorial function and print the result

print("Factorial of", num, "is", factorial(num))

Output:
31. Write a Python program to check the validity of a password given by user?

Program:

def is_valid_password(password):

# Check length

if len(password) < 8 or len(password) > 20:

return False

# Check for uppercase, lowercase, digit, and special character

has_upper = any(char.isupper() for char in password)

has_lower = any(char.islower() for char in password)

has_digit = any(char.isdigit() for char in password)

has_special = any(char in "!@#$%^&*()-_+=<>,.?/:;{}[]" for char in password)

# All conditions must be True for the password to be valid

return has_upper and has_lower and has_digit and has_special

# Get password input from user

password = input("Enter your password: ")

# Check password validity and print the result

if is_valid_password(password):

print("Password is valid.")

else:

print("Password is not valid.")

Output:
32. The password should satisfied
following criteria:
a. Contain at least 1 number between 0 and 9
b. Contain at least 1 letter between A and Z
c. Contain at least 1 character from $, #, @,*
d. Minimum length of password : 8
e. Maximum length of password : 20
Program:

import re

def is_valid_password(password):

""" Function to check the validity of a password based on specified criteria.

Criteria:

i) Contain at least 1 letter between a and z

ii) Contain at least 1 number between 0 and 9

iii) Contain at least 1 letter between A and Z

iv) Contain at least 1 character from $, #, @, *

v) Minimum length of password: 8

vi) Maximum length of password: 20

Args:

password (str): The password to be checked.

Returns:

bool: True if the password is valid, False otherwise.”””

# Check length

if len(password) < 8 or len(password) > 20:

return False

# Check if password contains at least 1 lowercase letter, 1 uppercase letter, 1 digit, and 1 special character

if not re.search("[a-z]", password):

return False

if not re.search("[A-Z]", password):

return False

if not re.search("[0-9]", password):

return False

if not re.search("[$#@*]", password):

return False

# All conditions are satisfied


# All conditions are satisfied

return True

# Get password input from user

password = input("Enter your password: ")

# Check password validity and print the result

if is_valid_password(password):

print("Password is valid.")

else:

print("Password is not valid.")

Output:
33. Draw bar graph using matplotlib and decorate it by adding various elements?

Program:

import matplotlib.pyplot as plt

# Data for the bar graph


categories = ['Category A', 'Category B', 'Category C', 'Category D']values =
[25, 40, 30, 35]

# Create the bar graph


plt.bar(categories, values)

# Add labels and title


plt.xlabel('Categories')
plt.ylabel('Values') plt.title('Bar
Graph')

# Add gridlines
plt.grid(True, linestyle='--', alpha=0.5)

# Customize the appearance


plt.xticks(rotation=45) plt.ylim(0,
max(values) + 5)

# Add data labels


for i, value in enumerate(values):
plt.text(i, value + 1, str(value), ha='center')

# Show the plotplt.show()

Output:
34. Prepare the pandas dataframe from csv file?

Program:

import pandas as pd

def main():

# Load CSV file into a DataFrame

data = pd.read_csv(r'C:\Users\anike\OneDrive\Desktop\csvexample1.csv')

#csv_file = "csvexample1.csv" # Replace "your_file.csv" with the path to your CSV


file

#df = pd.read_csv(data)

# Display the DataFrame

print("DataFrame from CSV file:")

print(data)

if __name__ == "__main__":

main()

Output:
35. perform following operations. i) Fill all ‘NaN’ values with the mean of respective
column. ii) Display last 5 rows. d) Explain constructors in pythan with example.
Program:
36. Write a program to illustrate numpy array attributes/functions.
a. ndarray. Shape
b. np. zeros ( )
c. np. eye ( )
d. np. random. random ( )
Program:

import numpy as np

def main():

# Creating a 2D array

arr = np.array([[1, 2, 3],

[4, 5, 6]])

# i) ndarray.shape - returns the shape of the array

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

# ii) np.zeros() - creates an array filled with zeros

zeros_arr = np.zeros((2, 3))

print("Array filled with zeros:")

print(zeros_arr)

# iii) np.eye() - creates a 2-D array with ones on the diagonal and zeros elsewhere

eye_arr = np.eye(3)

print("2-D array with ones on the diagonal:")

print(eye_arr)

# iv) np.random.random() - returns random floats in the half-open interval [0.0, 1.0)

random_arr = np.random.random((2, 3))

print("Random array:")

print(random_arr)

if __name__ == "__main__":

main()
Output:
37. Read data from csv five and create dataframe. Perform following operations. i)
Display list of all columns. ii) Display data with last three rows and first three
columns
Program:

import pandas as pd

# Read the CSV file into a dataframe

data = pd.read_csv(r'C:\Users\anike\OneDrive\Desktop\csvexample1.csv')

#df = pd.read_csv('C:\Users\anike\OneDrive\Desktop\csvexample1.csv')

# i) Display list of all columns

print("List of all columns:")

print(data.columns.tolist())

# ii) Display data with last three rows and first three columns

print("\nData with last three rows and first three columns:")

print(data.iloc[-3:, :3])

Output:
38 Draw line graph using matplot lib and decorate it by adding
various elements. Usesuitable data?
Program:

import matplotlib.pyplot as plt

# Data for the line graphx =


[1, 2, 3, 4, 5]
y = [5, 3, 7, 2, 6]

# Create the line graph


plt.plot(x, y)

# Add labels and title


plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Graph')

# Add gridlines
plt.grid(True, linestyle='--', alpha=0.5)

# Customize the appearance


plt.xticks(x) plt.yticks(range(1,
max(y) + 1))plt.xlim(min(x), max(x))
plt.ylim(0, max(y) + 1)

# Add data labels


for i, j in zip(x, y):
plt.text(i, j, str(j), ha='center', va='bottom')

# Show the plot


plt.show()
Output:

You might also like