Python Imp Questions With Answers
Q.1. Write a mongo DB program in python to create a 'student' collection having fields: Roll No,
Name, Course, Marks, Grade point. Write a code to perform following operations
i) Insert 5 documents into Student collection.
ii) Find students having marks between 80 to 90.
iii) Update name of a of a student whose roll no.is 5.
iv) Display top 3 students according to their grade points.
v) Display students having highest grade points.
vi) Find all students having course 'MCA'
vii) Display all student's in the descending order of marks.
Ans:
from pymongo import MongoClient
# Connect to MongoDB
client = MongoClient('mongodb://localhost:27017/')
# Select database and collection
db = client['school']
student_collection = db['student']
# i) Insert 5 documents into Student collection
students = [
{"Roll No": 1, "Name": "John", "Course": "BCA", "Marks": 85, "Grade point": 8.5},
{"Roll No": 2, "Name": "Alice", "Course": "MCA", "Marks": 75, "Grade point": 7.5},
{"Roll No": 3, "Name": "Bob", "Course": "BBA", "Marks": 88, "Grade point": 8.8},
{"Roll No": 4, "Name": "Eve", "Course": "MCA", "Marks": 92, "Grade point": 9.2},
{"Roll No": 5, "Name": "Charlie", "Course": "BCA", "Marks": 90, "Grade point": 9.0}
# Insert documents into collection
student_collection.insert_many(students)
print("Inserted 5 student documents.")
# ii) Find students having marks between 80 and 90
students_in_range = student_collection.find({"Marks": {"$gte": 80, "$lte": 90}})
print("\nStudents with marks between 80 and 90:")
for student in students_in_range:
print(student)
# iii) Update the name of the student whose roll no. is 5
student_collection.update_one(
{"Roll No": 5},
{"$set": {"Name": "Chuck"}}
print("\nUpdated the name of student with Roll No 5.")
# iv) Display top 3 students according to their grade points
top_students = student_collection.find().sort("Grade point", -1).limit(3)
print("\nTop 3 students by grade points:")
for student in top_students:
print(student)
# v) Display students having highest grade points
highest_grade_point = student_collection.find().sort("Grade point", -1).limit(1)
print("\nStudent with the highest grade point:")
for student in highest_grade_point:
print(student)
# vi) Find all students having course 'MCA'
mca_students = student_collection.find({"Course": "MCA"})
print("\nStudents with course 'MCA':")
for student in mca_students:
print(student)
# vii) Display all students in the descending order of marks
students_desc_marks = student_collection.find().sort("Marks", -1)
print("\nStudents in descending order of marks:")
for student in students_desc_marks:
print(student)
# Close the connection to MongoDB
client.close()
Q.2Write a mongo DB program in python to create a "Books" collection having fields: Title, Author,
Publisher, Price. Write a code to perform following operations: i) Insert 5 documents into Books
collection ii) Retrieve books whose publisher is “pearson”. iii) Retrieve books whose price is
between 400 to 600. iv) Retrieve books in the descending order of price. v) Update the price of
book by 10% whose title is 'Python'. vi) Update the title of a book whose author is 'Guido' and
publisher is 'BPB'. vii) Delete books whose price is greater than 500.
Ans:
from pymongo import MongoClient
# Connect to MongoDB
client = MongoClient('mongodb://localhost:27017/')
# Select database and collection
db = client['bookstore']
books_collection = db['Books']
# i) Insert 5 documents into Books collection
books = [
{"Title": "Python Basics", "Author": "Guido", "Publisher": "Pearson", "Price": 450},
{"Title": "JavaScript Essentials", "Author": "John Doe", "Publisher": "O'Reilly", "Price": 350},
{"Title": "MongoDB for Beginners", "Author": "Jane Smith", "Publisher": "BPB", "Price": 550},
{"Title": "Node.js Development", "Author": "Guido", "Publisher": "BPB", "Price": 600},
{"Title": "Advanced Python", "Author": "Guido", "Publisher": "Pearson", "Price": 650}
# Insert documents into the collection
books_collection.insert_many(books)
print("Inserted 5 books into the 'Books' collection.")
# ii) Retrieve books whose publisher is 'Pearson'
pearson_books = books_collection.find({"Publisher": "Pearson"})
print("\nBooks published by Pearson:")
for book in pearson_books:
print(book)
# iii) Retrieve books whose price is between 400 to 600
books_in_range = books_collection.find({"Price": {"$gte": 400, "$lte": 600}})
print("\nBooks with price between 400 and 600:")
for book in books_in_range:
print(book)
# iv) Retrieve books in the descending order of price
books_desc_price = books_collection.find().sort("Price", -1)
print("\nBooks sorted in descending order of price:")
for book in books_desc_price:
print(book)
# v) Update the price of the book titled 'Python Basics' by 10%
updated_price = books_collection.update_one(
{"Title": "Python Basics"},
{"$mul": {"Price": 1.10}} # Increase price by 10%
)
print("\nUpdated the price of 'Python Basics' by 10%.")
# vi) Update the title of a book whose author is 'Guido' and publisher is 'BPB'
updated_title = books_collection.update_one(
{"Author": "Guido", "Publisher": "BPB"},
{"$set": {"Title": "Node.js for Beginners"}}
print("\nUpdated the title of the book by Guido published by BPB.")
# vii) Delete books whose price is greater than 500
deleted_books = books_collection.delete_many({"Price": {"$gt": 500}})
print(f"\nDeleted {deleted_books.deleted_count} books whose price is greater than 500.")
# Close the connection
client.close()
Q.3.Write a python program to check whether the given number is prime or not using function.
Ans:
def is_prime(number):
if number <= 1:
return False
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
return False
return True
# Input from user
number = int(input("Enter a number: "))
if is_prime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")
Q.4.What is List in python? Explain insert, append, extend and remove function related to list
along with example.
Ans:
A list is a collection data type in Python that is ordered, mutable (can be changed), and allows
duplicate elements. Lists are defined using square brackets ([]).
List Operations:
insert(index, element): Adds an element at a specific position in the list.
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, 'orange') # Insert 'orange' at index 1
print(fruits) # Output: ['apple', 'orange', 'banana', 'cherry']
append(element): Adds an element at the end of the list.
python
Copy
fruits.append('kiwi') # Append 'kiwi' at the end
print(fruits) # Output: ['apple', 'orange', 'banana', 'cherry', 'kiwi']
extend(iterable): Adds all elements from another iterable (e.g., list, tuple) to the end of the
list.
python
Copy
fruits.extend(['mango', 'grapes']) # Extend the list with another list
print(fruits) # Output: ['apple', 'orange', 'banana', 'cherry', 'kiwi', 'mango', 'grapes']
remove(element): Removes the first occurrence of the specified element.
python
Copy
fruits.remove('banana') # Removes 'banana'
print(fruits) # Output: ['apple', 'orange', 'cherry', 'kiwi', 'mango', 'grapes']
Q.5 Differentiate between list and tuple in python.
Ans:
List:
o Lists are mutable (can be modified).
o Defined using square brackets: [].
o Example: my_list = [1, 2, 3]
Tuple:
o Tuples are immutable (cannot be modified).
o Defined using parentheses: ().
o Example: my_tuple = (1, 2, 3)
Key Differences:
Feature List Tuple
Mutability Mutable (can be changed) Immutable (cannot be changed)
Syntax [] (square brackets) () (parentheses)
When you need a collection of items When you need a collection of items that
Use Case
that might change should remain constant
Slower compared to tuples due to
Performance Faster than lists due to immutability
mutability
Q.6. Python Program to Implement Area Class to Calculate Area of Circle
Ans:
import math
# Class to calculate area
class Area:
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return math.pi * (self.radius ** 2)
# Create an object of the Area class
radius = float(input("Enter the radius of the circle: "))
circle = Area(radius)
# Calculate and display the area
area = circle.calculate_area()
print(f"The area of the circle with radius {radius} is {area:.2f}.")
Q.7.Write a python program to valid ate email using regular expression.
Ans:
import re
# Function to validate email
def validate_email(email):
# Regular expression for validating email
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
# Match the email against the pattern
if re.match(pattern, email):
return True
return False
# Input email
email = input("Enter an email address: ")
# Validate and print result
if validate_email(email):
print(f"{email} is a valid email address.")
else:
print(f"{email} is not a valid email address.")
Q.8.Write a python program to validate password using regular expression.
Ans:
import re
# Function to validate password
def validate_password(password):
# Regular expression pattern for a valid password
pattern = r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@#$%^&+=!]).{8,}$'
# Match the password against the pattern
if re.match(pattern, password):
return True
else:
return False
# Input password
password = input("Enter your password: ")
# Validate and print result
if validate_password(password):
print("Password is valid.")
else:
print("Password is invalid. Ensure it meets the following criteria:")
print("- At least 8 characters long")
print("- Contains at least one uppercase letter")
print("- Contains at least one lowercase letter")
print("- Contains at least one digit")
print("- Contains at least one special character (e.g., @, #, $, %, ^, &, +, =, !)")
Q.9.Write a python program to validate URL using regular expression. Also explain the meaning of
each and every special character of the regular expression used by you in this program.
Ans:
import re
# Function to validate URL
def validate_url(url):
# Regular expression pattern for a valid URL
pattern = r'^(https?|ftp)://(?:www\.)?[a-zA-Z0-9-]+\.[a-zA-Z]{2,6}(/[\w\-\.~!$&\'()*+,;=:@%]*)*(\?
[a-zA-Z0-9&=]*)?(#[a-zA-Z0-9\-]*)?$'
# Match the URL against the pattern
if re.match(pattern, url):
return True
else:
return False
# Input URL
url = input("Enter a URL: ")
# Validate and print result
if validate_url(url):
print(f"'{url}' is a valid URL.")
else:
print(f"'{url}' is not a valid URL.")
Q.10.Write a python program which will throw exception if the value entered by user is less than
Zero.
Ans:
def check_value(value):
if value < 0:
raise ValueError("Entered value is less than zero. Please enter a positive number.")
return value
try:
user_input = int(input("Enter a number: "))
check_value(user_input)
print("You entered:", user_input)
except ValueError as e:
print(e)
Q.11. Write a python program to check if the input year is leap year or not. Validate the input.
Ans:
def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
while True:
try:
year = int(input("Enter a year: "))
if year < 0:
raise ValueError("Year must be a positive integer.")
break
except ValueError as ve:
print(ve)
if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
Q.12. Write a python program to find the factorial of a number using recursion.(repeat question)
Ans:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
number = int(input("Enter a number to find the factorial: "))
if number < 0:
print("Factorial is not defined for negative numbers.")
else:
print(f"Factorial of {number} is {factorial(number)}")
Q.13. What is inheritance? Explain the concept of multiple inheritance with the help of suitable
example.
Ans:
Inheritance is a mechanism in object-oriented programming that allows you to define a class (child
class) that inherits the attributes and methods from another class (parent class). It helps to reuse
code and establish a relationship between classes.
Multiple Inheritance occurs when a class inherits from more than one parent class.
class Animal:
def speak(self):
print("Animal speaks")
class Bird:
def fly(self):
print("Bird can fly")
class Parrot(Animal, Bird):
def color(self):
print("Parrot is green")
parrot = Parrot()
parrot.speak() # Inherited from Animal
parrot.fly() # Inherited from Bird
parrot.color() # Method in Parrot
Q.14. What is tuple? What is the difference between list and tuple? Explain with example.
Ans:
A tuple is an ordered collection of elements, similar to a list, but it is immutable (cannot be modified
after creation).
Differences:
Feature List Tuple
Immutable (cannot be
Mutability Mutable (can be changed)
changed)
Syntax Defined using [] Defined using ()
Performance Slower than tuple Faster than list
When elements should not
Use Case When elements need to be changed
change
Example:
# List Example
my_list = [1, 2, 3]
my_list[0] = 10
print(my_list) # Output: [10, 2, 3]
# Tuple Example
my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # This will raise an error
print(my_tuple) # Output: (1, 2, 3)
Q.15. Write a python program to print the sum of natural numbers using recursion.
Ans:
def sum_natural_numbers(n):
if n == 1:
return 1
else:
return n + sum_natural_numbers(n - 1)
number = int(input("Enter a number: "))
if number < 1:
print("Please enter a positive integer.")
else:
print(f"Sum of first {number} natural numbers is {sum_natural_numbers(number)}")
Q.16. What is inheritance in python? Explain the concept of multilevel inheritance with the help of
suitable example.
Ans:
Multilevel Inheritance occurs when a class inherits from a class that has already inherited from
another class.
Example:
class Animal:
def speak(self):
print("Animal speaks")
class Mammal(Animal):
def walk(self):
print("Mammal can walk")
class Dog(Mammal):
def bark(self):
print("Dog barks")
dog = Dog()
dog.speak() # Inherited from Animal
dog.walk() # Inherited from Mammal
dog.bark() # Method in Dog
Q.17. Write a function to accept string from user and it will return reverse each word of string.
Ans:
def reverse_words(string):
words = string.split() # Split the string into words
reversed_words = [word[::-1] for word in words] # Reverse each word
return ' '.join(reversed_words) # Join the reversed words back into a string
input_string = input("Enter a sentence: ")
print("Reversed words:", reverse_words(input_string))
Q.18. Write a python program to reverse each word of “data.txt” file.(repeat question)
Ans:
def reverse_words_in_file(file_path):
with open(file_path, 'r') as file:
content = file.read()
reversed_content = ' '.join([word[::-1] for word in content.split()])
with open(file_path, 'w') as file:
file.write(reversed_content)
# Assuming the file 'data.txt' exists
reverse_words_in_file('data.txt')
Q.19. Write a python program to accept decimal number and print its octal and hexadecimal
equivalent.
Ans:
decimal_number = int(input("Enter a decimal number: "))
print(f"Octal: {oct(decimal_number)}")
print(f"Hexadecimal: {hex(decimal_number)}")
Q.20. Write a python program to read the contents of file and display occurrance of given
character.
Ans:
def count_char_in_file(file_path, char):
with open(file_path, 'r') as file:
content = file.read()
count = content.count(char)
print(f"The character '{char}' appears {count} times in the file.")
# Example usage
count_char_in_file('data.txt', 'a')
Q.21. What is dictionary in Python? Explain with examples.
Ans:
A dictionary in Python is an unordered collection of key-value pairs, where each key must be unique.
Example:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
# Accessing values using keys
print(my_dict['name']) # Output: John
print(my_dict.get('age')) # Output: 25
# Adding a new key-value pair
my_dict['email'] = 'john@example.com'
# Deleting a key-value pair
del my_dict['city']
print(my_dict) # Output: {'name': 'John', 'age': 25, 'email': 'john@example.com'}
Q.22. Write user defined exception program in python which will except age as an input from the
user and check whether the user is eligible for voting or not. If age<18 it should raise the exception
as ‘Not eligible for voting’ (Repeat question).
Ans:
class VotingEligibilityError(Exception):
pass
def check_voting_age(age):
if age < 18:
raise VotingEligibilityError("Not eligible for voting")
else:
print("Eligible for voting")
try:
age = int(input("Enter your age: "))
check_voting_age(age)
except VotingEligibilityError as e:
print(e)
Q.23. Write user defined exception program in python which will find the factorial of a number. If
number is less than zero it should raise the exception as 'Invalid Input'.
Ans:
class InvalidInputError(Exception):
pass
def factorial(n):
if n < 0:
raise InvalidInputError("Invalid input: Factorial is not defined for negative numbers.")
elif n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
try:
number = int(input("Enter a number: "))
print(f"Factorial: {factorial(number)}")
except InvalidInputError as e:
print(e)
Q.24. Write a Note on : Modules and packages in Python.
Ans:
Modules: A module is a file containing Python definitions and statements. It allows us to
break down large programs into smaller, manageable files.
Packages: A package is a collection of modules grouped together under a common directory.
Example:
# mymodule.py
def greet():
print("Hello from the module!")
# main.py
import mymodule
mymodule.greet()
Q.25. Create a class student having attributes 'First Name', 'Last Name', Qualification' and methods
'update Qualification', 'Display details', and a constructor to initialize the values. Write main
program to demonstrate the use of student class.
Ans:
class Student:
def __init__(self, first_name, last_name, qualification):
self.first_name = first_name
self.last_name = last_name
self.qualification = qualification
def update_qualification(self, new_qualification):
self.qualification = new_qualification
def display_details(self):
print(f"Name: {self.first_name} {self.last_name}")
print(f"Qualification: {self.qualification}")
# Main program
student = Student("John", "Doe", "BSc")
student.display_details()
student.update_qualification("MSc")
student.display_details()
Q.26.Write multithread program, where one thread prints square of a number and another thread
prints cube of numbers. Also display the total time taken for execution.
Ans:
import threading
import time
# Function to print square of numbers
def print_square(num):
for i in range(1, num+1):
print(f"Square of {i}: {i*i}")
# Function to print cube of numbers
def print_cube(num):
for i in range(1, num+1):
print(f"Cube of {i}: {i*i*i}")
# Record start time
start_time = time.time()
# Number to print squares and cubes
num = 5
# Create threads
thread1 = threading.Thread(target=print_square, args=(num,))
thread2 = threading.Thread(target=print_cube, args=(num,))
# Start threads
thread1.start()
thread2.start()
# Wait for both threads to finish
thread1.join()
thread2.join()
# Record end time
end_time = time.time()
print(f"\nTotal time taken: {end_time - start_time} seconds")
Q.27. Write a multithreading program where one thread prints cube of number and other thread
print square of number.
Ans:
import threading
import time
# Function to print cube of numbers
def print_cube(num):
for i in range(1, num+1):
print(f"Cube of {i}: {i*i*i}")
# Function to print square of numbers
def print_square(num):
for i in range(1, num+1):
print(f"Square of {i}: {i*i}")
# Record start time
start_time = time.time()
# Number to print squares and cubes
num = 5
# Create threads
thread1 = threading.Thread(target=print_cube, args=(num,))
thread2 = threading.Thread(target=print_square, args=(num,))
# Start threads
thread1.start()
thread2.start()
# Wait for both threads to finish
thread1.join()
thread2.join()
# Record end time
end_time = time.time()
# Display total time taken
print(f"\nTotal time taken: {end_time - start_time} seconds")
Q.28. Write a multithreading program, where one thread prints square of a number and another
thread prints factorial of a number. Also display the total time taken for the execution.
Ans:
import threading
import time
# Function to print square of numbers
def print_square(num):
for i in range(1, num+1):
print(f"Square of {i}: {i*i}")
# Function to calculate factorial of numbers
def factorial(num):
result = 1
for i in range(1, num+1):
result *= i
print(f"Factorial of {num}: {result}")
# Record start time
start_time = time.time()
# Number to print square and factorial
num = 5
# Create threads
thread1 = threading.Thread(target=print_square, args=(num,))
thread2 = threading.Thread(target=factorial, args=(num,))
# Start threads
thread1.start()
thread2.start()
# Wait for both threads to finish
thread1.join()
thread2.join()
# Record end time
end_time = time.time()
# Display total time taken
print(f"\nTotal time taken: {end_time - start_time} seconds")
Q.29. Explain anonymous function with example.
Ans:
An anonymous function in Python is a function defined using the lambda keyword. It is a small, one-
line function that does not have a name.
Example:
# Regular function
def add(a, b):
return a + b
# Lambda function (Anonymous function)
add_lambda = lambda a, b: a + b
print(add(5, 10)) # Output: 15
print(add_lambda(5, 10)) # Output: 15
Q.30. Do the following operations on dictionaries :
i) Initialize two dictionaries with key & value pair.
ii) Find keys that are in first and not in second dictionary
i) Initialize Two Dictionaries and Find Keys in the First Dictionary but Not in the Second
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'b': 2, 'c': 4, 'd': 5}
# Keys in dict1 but not in dict2
keys_in_dict1_not_in_dict2 = dict1.keys() - dict2.keys()
print(f"Keys in dict1 but not in dict2: {keys_in_dict1_not_in_dict2}")
ii) Operations on Dictionaries
1. Initialize Dictionaries:
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
2. Find Keys in the First Dictionary but Not in the Second:
keys_in_dict1_not_in_dict2 = dict1.keys() - dict2.keys()
print(f"Keys in dict1 but not in dict2: {keys_in_dict1_not_in_dict2}")
Q.31. Write a python program to extract email from text file.
Ans:
import re
def extract_email(file_path):
with open(file_path, 'r') as file:
text = file.read()
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)
return emails
emails = extract_email('data.txt')
print("Extracted Emails:", emails)
Q.32. Write a program that accept the string from user and display the same string after removing
vowels from it.
Ans:
def remove_vowels(input_string):
vowels = "aeiouAEIOU"
result = ''.join([char for char in input_string if char not in vowels])
return result
input_string = input("Enter a string: ")
print(f"String after removing vowels: {remove_vowels(input_string)}")
Q.33. Write a program to check whether entered string & number is palindrome or not.
Ans:
def check_palindrome(input_str):
return input_str == input_str[::-1]
input_str = input("Enter a string or number: ")
if check_palindrome(input_str):
print(f"{input_str} is a palindrome.")
else:
print(f"{input_str} is not a palindrome.")
Q.34. Write a python program to perform following operations. on MongoDB Database. [5]
i) Create collection “EMP” with fields: Emp-name, Emp- mobile, Emp, sal, Age
ii) Insert 5 documents.
iii) Find the employees getting salary between 5000 to 10000.
iv) Update mobile number for the employee named as “Riddhi”
v) Display all employees in the order of “Age”
Ans:
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['company']
collection = db['EMP']
# ii) Insert 5 documents
employees = [
{'Emp-name': 'Riddhi', 'Emp-mobile': '12345', 'Emp-sal': 6000, 'Age': 25},
{'Emp-name': 'John', 'Emp-mobile': '67890', 'Emp-sal': 7000, 'Age': 30},
{'Emp-name': 'Alice', 'Emp-mobile': '11223', 'Emp-sal': 8000, 'Age': 28},
{'Emp-name': 'Bob', 'Emp-mobile': '44556', 'Emp-sal': 9000, 'Age': 35},
{'Emp-name': 'Eve', 'Emp-mobile': '77889', 'Emp-sal': 10000, 'Age': 40}
]
collection.insert_many(employees)
# iii) Find employees getting salary between 5000 and 10000
result = collection.find({"Emp-sal": {"$gte": 5000, "$lte": 10000}})
for emp in result:
print(emp)
# iv) Update mobile number for employee named 'Riddhi'
collection.update_one({'Emp-name': 'Riddhi'}, {'$set': {'Emp-mobile': '99999'}})
# v) Display employees in order of Age
result = collection.find().sort("Age")
for emp in result:
print(emp)
Q.35. Write a program for synchronization of threads using RLOCK. Accept the two numbers from
user and calculate factorial of both numbers simultaneously.
Ans:
import threading
# Function to calculate factorial
def factorial(num, lock):
lock.acquire()
result = 1
for i in range(1, num + 1):
result *= i
print(f"Factorial of {num} is {result}")
lock.release()
lock = threading.RLock()
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
thread1 = threading.Thread(target=factorial, args=(num1, lock))
thread2 = threading.Thread(target=factorial, args=(num2, lock))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
Q.36. Write a Python program to check the validity of a password given by user. The password
should satisfy following 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
Ans:
import re
def validate_password(password):
pattern = r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$#@*]).{8,20}$"
if re.match(pattern, password):
print("Valid password.")
else:
print("Invalid password. It must contain: 1 letter, 1 digit, 1 special character, and length between
8-20 characters.")
password = input("Enter a password: ")
validate_password(password)
Q.37. Write a program to check the number entered by user is even or odd. Program should accept
integer digits only.
Ans:
try:
num = int(input("Enter an integer: "))
if num % 2 == 0:
print(f"{num} is Even")
else:
print(f"{num} is Odd")
except ValueError:
print("Please enter a valid integer.")
Q.38. 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.
Ans:
fruits = ["Apple", "Banana", "Orange"]
fruits.append("Mango")
fruits.sort()
fruits.remove("Banana")
del fruits[-1]
print(f"Updated fruits list: {fruits}")
Q.39. Write a python function to check the given number is even or odd. Handle suitable
exceptions.
Ans:
def check_even_odd(num):
if num % 2 == 0:
return "Even"
else:
return "Odd"
try:
num = int(input("Enter a number: "))
print(f"The number is {check_even_odd(num)}.")
except ValueError:
print("Please enter a valid integer.")
Q.40. Set, list, tuple, dictionary (create, insert, delete , remove , count , length ) all operation each.
Ans:
1. List
✅ Create
my_list = [1, 2, 3, 4]
✅ Insert
my_list.append(5) # Add at end
my_list.insert(2, 99) # Insert 99 at index 2
✅ Delete
del my_list[1] # Delete by index
✅ Remove
my_list.remove(99) # Remove by value
✅ Count
my_list.count(4) # Count occurrences of 4
✅ Length
len(my_list)
✅ 2. Tuple
(Note: Tuples are immutable)
✅ Create
my_tuple = (1, 2, 3, 4)
❌ Insert / Delete / Remove
You cannot insert, delete, or remove directly.
But you can convert to list, modify, then convert back:
temp = list(my_tuple)
temp.append(5)
my_tuple = tuple(temp)
✅ Count
my_tuple.count(2)
✅ Length
len(my_tuple)
✅ 3. Set
✅ Create
my_set = {1, 2, 3}
✅ Insert
my_set.add(4)
✅ Delete
my_set.discard(2) # Doesn't raise error if not found
# or
my_set.remove(3) # Raises error if not found
✅ Remove
Already shown above: remove() or discard()
✅ Length
len(my_set)
✅ 4. Dictionary
✅ Create
my_dict = {"a": 1, "b": 2}
✅ Insert
my_dict["c"] = 3
✅ Delete
del my_dict["a"]
✅ Remove
my_dict.pop("b")
✅ Count
You can check count of keys or values manually:
list(my_dict.values()).count(3)
✅ Length
len(my_dict)