python
Q.Write a Python program to find number is greater or smaller from list which is named mylist.
Write manual code
ans)
# Define the list
mylist = [5, 10, 3, 8, 15]
# Initialize variables to store the greater and smaller numbers
greater_number = mylist[0]
smaller_number = mylist[0]
# Iterate through the list
for num in mylist:
if num > greater_number:
greater_number = num
elif num < smaller_number:
smaller_number = num
# Print the results
print("Greater number:", greater_number)
print("Smaller number:", smaller_number)
Q.Demonstrate various operations on String and tuple. String is " Hello friends how are you", Tuple name is MyTuple
ans)
# Define the string
my_string = "Hello friends how are you"
# 1. Length of the string
print("Length of the string:", len(my_string))
# 2. Accessing characters by index
print("Character at index 7:", my_string[7])
# 3. Slicing
print("Sliced substring from index 6 to 13:", my_string[6:14])
# 4. Concatenation
new_string = my_string + ", I hope you're doing well."
print("Concatenated string:", new_string)
# 5. Splitting
split_string = my_string.split()
print("Split string:", split_string)
# 6. Joining
joined_string = " ".join(split_string)
print("Joined string:", joined_string)
# 7. Case conversion
print("Uppercase:", my_string.upper())
print("Lowercase:", my_string.lower())
# 8. Replacing
replaced_string = my_string.replace("friends", "buddies")
print("Replaced string:", replaced_string)
# 9. Finding substrings
print("Index of 'friends':", my_string.find("friends"))
# 10. Checking for substrings
print("Contains 'how'?", 'how' in my_string)
# Define the tuple
my_tuple = (1, 2, 3, 4, 5)
# 1. Length of the tuple
print("Length of the tuple:", len(my_tuple))
# 2. Accessing elements by index
print("Element at index 2:", my_tuple[2])
# 3. Slicing
print("Sliced elements from index 1 to 3:", my_tuple[1:4])
# 4. Concatenation
new_tuple = my_tuple + (6, 7, 8)
print("Concatenated tuple:", new_tuple)
# 5. Repetition
repeated_tuple = my_tuple * 3
print("Repeated tuple:", repeated_tuple)
# 6. Tuple unpacking
a, b, c, d, e = my_tuple
print("Unpacked elements:", a, b, c, d, e)
# 7. Checking for element existence
print("Is 3 in the tuple?", 3 in my_tuple)
# 8. Finding index of an element
print("Index of 4:", my_tuple.index(4))
# 9. Counting occurrences of an element
print("Count of 3:", my_tuple.count(3))
Q.Create a File newfile. txt. Write four to six lines in your file and perform following, number of line in file, number of words in line, number of vowels in file
ans)
# Create the file and write some lines
with open("newfile.txt", "w") as file:
file.write("This is line one.\n")
file.write("And this is line two.\n")
file.write("Line three has a few more words.\n")
file.write("Line four is shorter.\n")
# Initialize variables to count lines, words, and vowels
line_count = 0
word_count = 0
vowel_count = 0
# Open the file for reading
with open("newfile.txt", "r") as file:
# Count lines, words, and vowels
for line in file:
line_count += 1
words = line.split()
word_count += len(words)
for word in words:
for char in word:
if char.lower() in "aeiou":
vowel_count += 1
# Print the results
print("Number of lines in the file:", line_count)
print("Number of words in the file:", word_count)
print("Number of vowels in the file:", vowel_count)
Q.Python program to check the student's Grades in Examination based on following information. If Percentage is >80 "Outstanding", if Percentage>=70 and <80 "Distinction", if percentage>=60 and <70 "First Class", percentage >=50 and <60 "Second Class", percentage >=40 and <50 "Pass Class",
, percentage <40 "Fail
ans)
def calculate_grade(percentage):
if percentage > 80:
return "Outstanding"
elif percentage >= 70:
return "Distinction"
elif percentage >= 60:
return "First Class"
elif percentage >= 50:
return "Second Class"
elif percentage >= 40:
return "Pass Class"
else:
return "Fail"
def main():
# Get the percentage from the user
percentage = float(input("Enter the student's percentage: "))
# Check the grade and print the result
grade = calculate_grade(percentage)
print("Student's grade:", grade)
if __name__ == "__main__":
main()
Q.Write Python code to use array package and perform, create one-D array, two-D array, perform addition, multiplication and product of array
ans)
import numpy as np
# Create one-dimensional array
one_d_array = np.array([1, 2, 3, 4, 5])
print("One-dimensional array:")
print(one_d_array)
# Create two-dimensional array
two_d_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("\nTwo-dimensional array:")
print(two_d_array)
# Addition of arrays
array_sum = one_d_array + one_d_array
print("\nAddition of one-dimensional arrays:")
print(array_sum)
# Multiplication of arrays
array_product = one_d_array * one_d_array
print("\nMultiplication of one-dimensional arrays:")
print(array_product)
# Dot product of arrays
array_dot_product = np.dot(two_d_array, two_d_array)
print("\nDot product of two-dimensional arrays:")
print(array_dot_product)
Q. Write python program to create class name Student. Enter student names, class, rollno, Marks of two subjects and display total and average marks of student
ans)
class Student:
def __init__(self, name, student_class, roll_no, marks_subject1, marks_subject2):
self.name = name
self.student_class = student_class
self.roll_no = roll_no
self.marks_subject1 = marks_subject1
self.marks_subject2 = marks_subject2
def calculate_total_marks(self):
return self.marks_subject1 + self.marks_subject2
def calculate_average_marks(self):
total_marks = self.calculate_total_marks()
return total_marks / 2
def display_student_details(self):
print("Name:", self.name)
print("Class:", self.student_class)
print("Roll No:", self.roll_no)
print("Marks in Subject 1:", self.marks_subject1)
print("Marks in Subject 2:", self.marks_subject2)
print("Total Marks:", self.calculate_total_marks())
print("Average Marks:", self.calculate_average_marks())
# Create a student object
student1 = Student("John Doe", "XII", 101, 85, 90)
# Display student details
student1.display_student_details()
Q. Write a python program to calculate net salary of employee based on following data. Basic salary=16500, HRA=67%, DA=137%, TA=2%, NAAC=1500, Deduction- Professional Tax=200, PF=1800, Calculate gross Salary monthly and Yearly, Calculate net salary monthly and Yearly, Calculate income tax on employee salary yearly
ans)
class Employee:
def __init__(self, basic_salary, hra_percentage, da_percentage, ta_percentage, naac, professional_tax, pf):
self.basic_salary = basic_salary
self.hra_percentage = hra_percentage
self.da_percentage = da_percentage
self.ta_percentage = ta_percentage
self.naac = naac
self.professional_tax = professional_tax
self.pf = pf
def calculate_gross_salary(self):
hra_amount = self.basic_salary * self.hra_percentage / 100
da_amount = self.basic_salary * self.da_percentage / 100
ta_amount = self.basic_salary * self.ta_percentage / 100
return self.basic_salary + hra_amount + da_amount + ta_amount + self.naac
def calculate_net_salary(self):
gross_salary = self.calculate_gross_salary()
return gross_salary - (self.professional_tax + self.pf)
def calculate_annual_gross_salary(self):
return self.calculate_gross_salary() * 12
def calculate_annual_net_salary(self):
return self.calculate_net_salary() * 12
def calculate_income_tax(self):
annual_gross_salary = self.calculate_annual_gross_salary()
taxable_income = annual_gross_salary - 250000 # Assuming standard deduction of 2.5 lakh
if taxable_income <= 0:
return 0
elif 250000 < taxable_income <= 500000:
return taxable_income * 0.05
elif 500000 < taxable_income <= 1000000:
return 12500 + (taxable_income - 500000) * 0.2
else:
return 112500 + (taxable_income - 1000000) * 0.3
# Define employee data
basic_salary = 16500
hra_percentage = 67
da_percentage = 137
ta_percentage = 2
naac = 1500
professional_tax = 200
pf = 1800
# Create employee object
employee = Employee(basic_salary, hra_percentage, da_percentage, ta_percentage, naac, professional_tax, pf)
# Calculate and display results
print("Monthly Gross Salary:", employee.calculate_gross_salary())
print("Monthly Net Salary:", employee.calculate_net_salary())
print("Yearly Gross Salary:", employee.calculate_annual_gross_salary())
print("Yearly Net Salary:", employee.calculate_annual_net_salary())
print("Yearly Income Tax:", employee.calculate_income_tax())
Q.This Python program takes input from the user in the form of space-separated integers and creates a tuple from those values. It then finds the smallest and largest elements in the tuple and
prints them. (Use manual code, not built-in functions)
ans)
# Take input from the user
input_values = input("Enter space-separated integers: ")
# Split the input string into a list of integers
integers = [int(num) for num in input_values.split()]
# Initialize variables to hold the smallest and largest elements
smallest = None
largest = None
# Iterate through the list to find the smallest and largest elements
for num in integers:
if smallest is None or num < smallest:
smallest = num
if largest is None or num > largest:
largest = num
# Create a tuple from the list of integers
input_tuple = tuple(integers)
# Print the tuple and the smallest and largest elements
print("Tuple:", input_tuple)
print("Smallest element:", smallest)
print("Largest element:", largest)
Q.Write Python code to to create user defined function sum_of_digit to perform sum of digits of
user input (e.g. if user input is 5678 = 26)
ans)
def sum_of_digit(number):
# Convert the number to a string to iterate through each digit
number_str = str(number)
# Initialize variable to hold the sum
total_sum = 0
# Iterate through each digit in the string and add it to the sum
for digit in number_str:
total_sum += int(digit)
# Return the total sum
return total_sum
# Take input from the user
user_input = input("Enter a number: ")
# Convert the input to an integer and call the sum_of_digit function
number = int(user_input)
result = sum_of_digit(number)
# Print the result
print("Sum of digits of", number, "is", result)
Q.Write Python program to create parameterized constructor to take the name of emp, emp id and
employee basic salary. Take salary at run time and calculate salary for 12 months .
ans)
class Employee:
def __init__(self, name, emp_id, basic_salary):
self.name = name
self.emp_id = emp_id
self.basic_salary = basic_salary
def calculate_annual_salary(self):
return self.basic_salary * 12
# Input from user
name = input("Enter employee name: ")
emp_id = input("Enter employee ID: ")
basic_salary = float(input("Enter basic salary: "))
# Create employee object with parameterized constructor
employee = Employee(name, emp_id, basic_salary)
# Calculate and print annual salary
annual_salary = employee.calculate_annual_salary()
print("Annual salary for employee", name, "with ID", emp_id, "is:", annual_salary)
Q.Write Python program to take user string "Hello friends how are you, All the best for your practical examination" Use regular expression and find all words starting from 'H' letter, display the position of that word. Find 'Hello" word and replace it with 'Namaste"
ans)
import re
# User string
user_string = "Hello friends how are you, All the best for your practical examination"
# Find all words starting from 'H' letter and display their positions
words_starting_with_h = re.finditer(r'\bH\w+', user_string)
print("Words starting with 'H' and their positions:")
for match in words_starting_with_h:
print("Word:", match.group(), "Position:", match.start())
# Find 'Hello' word and replace it with 'Namaste'
new_string = re.sub(r'\bHello\b', 'Namaste', user_string)
print("\nString after replacing 'Hello' with 'Namaste':")
print(new_string)
Q.Write Python code to check given number is odd or even using user defined function
ans)
def check_odd_even(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"
# Take input from the user
num = int(input("Enter a number: "))
# Call the user-defined function to check if the number is odd or even
result = check_odd_even(num)
# Print the result
print("The number", num, "is", result)
Q.This Python program takes input from the user for key value pair for your dictionary. It then find the smallest and largest elements in the dictionary and prints them. (Use manual code, not built-in functions)
ans)
# Take input from the user for key-value pairs
n = int(input("Enter the number of key-value pairs: "))
# Initialize an empty dictionary
my_dict = {}
# Input key-value pairs from the user
for i in range(n):
key = input("Enter key: ")
value = int(input("Enter value: "))
my_dict[key] = value
# Find the smallest and largest elements in the dictionary
smallest_key = None
largest_key = None
smallest_value = None
largest_value = None
for key, value in my_dict.items():
if smallest_value is None or value < smallest_value:
smallest_value = value
smallest_key = key
if largest_value is None or value > largest_value:
largest_value = value
largest_key = key
# Print the smallest and largest elements
print("Smallest element:", smallest_key, "-", smallest_value)
print("Largest element:", largest_key, "-", largest_value)
Q.Write recursion function to calculate factorial of given number.
ans)
def factorial(n):
# Base case: if n is 0 or 1, return 1
if n == 0 or n == 1:
return 1
# Recursive case: multiply n by factorial of (n-1)
else:
return n * factorial(n - 1)
# Test the function with a number
number = int(input("Enter a number to calculate its factorial: "))
result = factorial(number)
print("Factorial of", number, "is", result)
Q.Write Python code read a file content from Myfile.text. Display contents of file
ans)
# Open the file in read mode
try:
with open("Myfile.txt", "r") as file:
# Read the entire contents of the file
file_contents = file.read()
# Display the contents of the file
print("Contents of the file Myfile.txt:")
print(file_contents)
except FileNotFoundError:
print("File not found. Please make sure the file 'Myfile.txt' exists.")
except Exception as e:
print("An error occurred:", e)
Q.Write Python code to perform addition of two integers using Lambda function
ans)
# Define the lambda function for addition
addition = lambda x, y: x + y
# Input two integers from the user
num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))
# Perform addition using the lambda function
result = addition(num1, num2)
# Print the result
print("Sum of", num1, "and", num2, "is", result)
Q.Write Python code to create user defined package named Mypackage. Create module named Factorial to calculate factorial of user input. Import module to display the factorial of given
number
ans)
# Factorial.py
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# main.py
from Mypackage.Factorial import factorial
# Input a number from the user
number = int(input("Enter a number to calculate its factorial: "))
# Calculate factorial using the imported module
result = factorial(number)
# Display the result
print("Factorial of", number, "is", result)
Q.Write Python code perform following operations on list, insert new elements in list, display index of fourth element in your list, sort list elements in ascending and descending order, remove list element from list
ans)
# Define a list
my_list = [10, 5, 8, 3, 12]
# Insert new elements into the list
my_list.append(7) # Append 7 to the end of the list
my_list.insert(2, 15) # Insert 15 at index 2
# Display index of the fourth element in the list
if len(my_list) >= 4:
print("Index of the fourth element:", my_list[3])
# Sort list elements in ascending order
sorted_list_ascending = sorted(my_list)
# Sort list elements in descending order
sorted_list_descending = sorted(my_list, reverse=True)
# Remove list element from list
my_list.remove(8) # Remove the element 8 from the list
# Display the updated list and sorted lists
print("Updated list:", my_list)
print("Sorted list in ascending order:", sorted_list_ascending)
print("Sorted list in descending order:", sorted_list_descending)
Q.Write Python code to create list of 5 subjects to store first element is name of subject, second element is internal marks out of 30, third element is End term marks out of 70. Create DataFrame named Result_Analysis. Give labels to DataFrame as Subject, Internal Marks, End_Term Marks.
Apply basic operations on DataFrame
ans)
import pandas as pd
# Create a list of lists containing subject details
subjects_data = [
["Math", 25, 60],
["Science", 28, 65],
["English", 20, 50],
["History", 22, 58],
["Geography", 24, 62]
]
# Define column labels for the DataFrame
columns = ["Subject", "Internal Marks", "End Term Marks"]
# Create a DataFrame named Result_Analysis
Result_Analysis = pd.DataFrame(subjects_data, columns=columns)
# Print the DataFrame
print("DataFrame - Result_Analysis:")
print(Result_Analysis)
# Apply basic operations on DataFrame
# Calculate total marks
Result_Analysis['Total Marks'] = Result_Analysis['Internal Marks'] + Result_Analysis['End Term Marks']
# Calculate average marks
Result_Analysis['Average Marks'] = Result_Analysis['Total Marks'] / 2
# Print updated DataFrame
print("\nUpdated DataFrame with Total Marks and Average Marks:")
print(Result_Analysis)
Q.Write Python program to create Base class Employee, Derived classes HR Dept. and IT Dept. <
Take name Empid, and salary. Display the details of employee of both the departments.
ans)
class Employee:
def __init__(self, name, emp_id, salary):
self.name = name
self.emp_id = emp_id
self.salary = salary
def display_details(self):
print("Name:", self.name)
print("Employee ID:", self.emp_id)
print("Salary:", self.salary)
class HRDept(Employee):
def __init__(self, name, emp_id, salary):
super().__init__(name, emp_id, salary)
class ITDept(Employee):
def __init__(self, name, emp_id, salary):
super().__init__(name, emp_id, salary)
# Create instances of employees in HR department
hr_employee1 = HRDept("John Doe", "HR101", 50000)
hr_employee2 = HRDept("Jane Smith", "HR102", 55000)
# Create instances of employees in IT department
it_employee1 = ITDept("Michael Johnson", "IT201", 60000)
it_employee2 = ITDept("Emma Brown", "IT202", 65000)
# Display details of employees in HR department
print("Details of employees in HR department:")
hr_employee1.display_details()
print()
hr_employee2.display_details()
print()
# Display details of employees in IT department
print("Details of employees in IT department:")
it_employee1.display_details()
print()
it_employee2.display_details()
Q. Write Python code to validate email Id using regular expressions
ans)
import re
def validate_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if re.match(pattern, email):
return True
else:
return False
# Test the function
email1 = "example@example.com"
email2 = "invalid_email@example"
print("Is", email1, "a valid email?", validate_email(email1))
print("Is", email2, "a valid email?", validate_email(email2))
Q.Write Python code to open a file name Python.txt. Add at least four lines in file and display all the contents on screen.
ans)
# Open the file in append mode and add at least four lines
with open("Python.txt", "a") as file:
file.write("Python is a powerful programming language.\n")
file.write("It is widely used for web development, data science, and more.\n")
file.write("Python has a simple and easy-to-learn syntax.\n")
file.write("It emphasizes readability and simplicity.\n")
# Open the file in read mode and display its contents
with open("Python.txt", "r") as file:
contents = file.read()
print(contents)
Q.Write Python code to demonstrate Built-in packages in Python
ans)
import random
# Generate a random integer between 1 and 100
random_number = random.randint(1, 100)
print("Random number:", random_number)
Q.Write Python code to find the given number is palindrome or not
ans)
def is_palindrome(number):
# Convert the number to a string
number_str = str(number)
# Check if the string is equal to its reverse
if number_str == number_str[::-1]:
return True
else:
return False
# Test the function
num = int(input("Enter a number: "))
if is_palindrome(num):
print(num, "is a palindrome")
else:
print(num, "is not a palindrome")
Q.Write Python code to overload arithmetic operators (any three).
ans)
class MyNumber:
def __init__(self, value):
self.value = value
# Overloading addition operator (+)
def __add__(self, other):
return self.value + other.value
# Overloading subtraction operator (-)
def __sub__(self, other):
return self.value - other.value
# Overloading multiplication operator (*)
def __mul__(self, other):
return self.value * other.value
# Create instances of MyNumber class
num1 = MyNumber(5)
num2 = MyNumber(3)
# Test overloaded arithmetic operators
print("Addition:", num1 + num2) # Output: 8
print("Subtraction:", num1 - num2) # Output: 2
print("Multiplication:", num1 * num2) # Output: 15
Q.Write Python code to perform basic set operations.
ans)
# Define two sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Print the sets
print("Set 1:", set1)
print("Set 2:", set2)
# Union of sets
union_set = set1.union(set2)
print("Union of sets:", union_set)
# Intersection of sets
intersection_set = set1.intersection(set2)
print("Intersection of sets:", intersection_set)
# Difference between sets
difference_set = set1.difference(set2)
print("Difference between set1 and set2:", difference_set)
# Symmetric difference between sets
symmetric_difference_set = set1.symmetric_difference(set2)
print("Symmetric difference between sets:", symmetric_difference_set)
Q.Write Python code to create file named file.txt. Change the name of file.txt with file1.txt. Remove
file1.txt
ans)
import os
# Create a file named file.txt
with open("file.txt", "w") as file:
file.write("This is a test file.")
# Rename the file from file.txt to file1.txt
os.rename("file.txt", "file1.txt")
print("File renamed successfully.")
# Remove the file file1.txt
os.remove("file1.txt")
print("File file1.txt removed successfully.")
Q.Write Python program to create user defined function to print number in reverse order
ans)
def print_reverse(number):
reversed_number = int(str(number)[::-1])
print("Number in reverse order:", reversed_number)
# Test the function
num = int(input("Enter a number: "))
print_reverse(num)
Q.Write a Python program to demonstrate multilevel inheritance. The base class name is GrandParent Create two classes which will be derived from related class which demonstrate
multilevel inheritance
ans)
# Define the base class GrandParent
class GrandParent:
def __init__(self):
print("GrandParent class constructor")
def display(self):
print("This is GrandParent class")
# Define the first derived class Parent
class Parent(GrandParent):
def __init__(self):
super().__init__()
print("Parent class constructor")
def show(self):
print("This is Parent class")
# Define the second derived class Child
class Child(Parent):
def __init__(self):
super().__init__()
print("Child class constructor")
def output(self):
print("This is Child class")
# Create an object of Child class
child_obj = Child()
# Demonstrate multilevel inheritance
child_obj.display()
child_obj.show()
child_obj.output()
Q.Write program to create file. Enter some contents in your file. Use readline, readlines) function
ans)
# Create a file named "example.txt" and enter some contents
with open("example.txt", "w") as file:
file.write("This is line 1.\n")
file.write("This is line 2.\n")
file.write("This is line 3.\n")
file.write("This is line 4.\n")
file.write("This is line 5.\n")
# Open the file in read mode
with open("example.txt", "r") as file:
# Use readline() to read one line at a time
print("Using readline():")
line = file.readline()
while line:
print(line.strip()) # strip() to remove the newline character
line = file.readline()
# Use readlines() to read all lines at once into a list
print("\nUsing readlines():")
lines = file.readlines()
for line in lines:
print(line.strip())
Comments
Post a Comment