You are on page 1of 36

#1.

Write a python code to check whether the input number is


prime or not

Code:-
# taking input from user
number = int(input("Enter any number: "))

# prime number is always greater than 1


if number > 1:
for i in range(2, number):
if (number % i) == 0:
print(number, "is not a prime number")
break
else:
print(number, "is a prime number")

# if the entered number is less than or equal to 1


# then it is not prime number
else:
print(number, "is not a prime number")
#2.
Write a python code which multiplies a given input
number till it reaches 24998, if output number>24998,
stop the code.

CODE:-
def multiply_until_24998(number):
result = number
count = 1

while result < 24998:


result *= number
count += 1

return result, count

given_number = float(input("Enter a number: "))

if given_number <= 0:
print("Please enter a positive number.")
else:
final_result, iterations = multiply_until_24998(given_number)
print(f"Final result: {final_result}")
print(f"Number of iterations: {iterations}")
#3.
Write a python code which divides a given input
number till it reaches 0.0001, if output
number<0.0001, stop the code.

CODE:-
def divide_until_0_0001(number):
result = number
count = 1

while result > 0.0001:


result /= number
count += 1

return result, count

given_number = float(input("Enter a number: "))

if given_number <= 0:
print("Please enter a positive number.")
else:
final_result, iterations = divide_until_0_0001(given_number)
print(f"Final result: {final_result}")
print(f"Number of iterations: {iterations}")
#4.
Write a python code to calculate log and
antilog of an input number.
CODE:-
import math

# Function to find the logarithm of a number


def find_log(number, base):
if number <= 0 or base <= 0 or base == 1:
return "Invalid input"
return math.log(number, base)

# Function to find the antilogarithm of a number


def find_antilog(log_value, base):
if base <= 0 or base == 1:
return "Invalid input"
antilog = math.pow(base, log_value)
return antilog
# Input number and base
number = float(input("Enter the number: "))
base = float(input("Enter the base: "))

# Calculate and display the logarithm


log_result = find_log(number, base)
print(f"Logarithm of {number} to the base {base}
is: {log_result}")

# Calculate and display the antilogarithm


antilog_result = find_antilog(log_result, base)
print(f"Antilogarithm of the above result to the
base {base} is: {antilog_result}")
#5.
Write a python code to plot sin,cos and
tan graphs.
CODE:-
import numpy as np
import matplotlib.pyplot as plt

# Generate x values
x = np.linspace(-2 * np.pi, 2 * np.pi, 1000) # Adjust the range as needed

# Calculate sine, cosine, and tangent values


sin_values = np.sin(x)
cos_values = np.cos(x)

# For tangent, we'll limit the range to -5 to 5


tan_x = np.linspace(-5, 5, 1000)
tan_values = np.tan(tan_x)

# Plot the graphs


plt.figure(figsize=(10, 6))

plt.subplot(131)
plt.plot(x, sin_values, label='sin(x)')
plt.title('Sine Function')
plt.grid()

plt.subplot(132)
plt.plot(x, cos_values, label='cos(x)', color='orange')
plt.title('Cosine Function')
plt.grid()

plt.subplot(133)
plt.plot(tan_x, tan_values, label='tan(x)', color='green')
plt.ylim(-5, 5) # Set y-axis limits for tangent graph
plt.title('Tangent Function')
plt.grid()

plt.tight_layout()
plt.show()
#6.
Write a python code to calculate area and
volume of sphere , hemisphere,cube and
cone.
CODE:-
import math

def calculate_area_sphere(radius):
return 4 * math.pi * radius**2

def calculate_volume_sphere(radius):
return (4/3) * math.pi * radius**3

def calculate_area_hemisphere(radius):
return 2 * math.pi * radius**2

def calculate_volume_hemisphere(radius):
return (2/3) * math.pi * radius**3

def calculate_area_cone(radius, height):


slant_height = math.sqrt(radius**2 + height**2)
return math.pi * radius * (radius + slant_height)
def calculate_volume_cone(radius, height):
return (1/3) * math.pi * radius**2 * height

def main():
print("Calculate Area or Volume?")
choice = input("Enter 'area' or 'volume': ").lower()

if choice not in ['area', 'volume']:


print("Invalid choice. Please enter 'area' or 'volume'.")
return

print("Select a shape:")
print("1. Sphere")
print("2. Hemisphere")
print("3. Cube")
print("4. Cone")

shape_choice = int(input("Enter your choice (1/2/3/4): "))

if shape_choice == 1:
radius = float(input("Enter the radius of the sphere: "))
if choice == 'area':
result = calculate_area_sphere(radius)
else:
result = calculate_volume_sphere(radius)
elif shape_choice == 2:
radius = float(input("Enter the radius of the hemisphere: "))
if choice == 'area':
result = calculate_area_hemisphere(radius)
else:
result = calculate_volume_hemisphere(radius)
elif shape_choice == 3:
side_length = float(input("Enter the side length of the cube: "))
if choice == 'area':
result = 6 * side_length ** 2
else:
result = side_length ** 3
elif shape_choice == 4:
radius = float(input("Enter the radius of the cone: "))
height = float(input("Enter the height of the cone: "))
if choice == 'area':
result = calculate_area_cone(radius, height)
else:
result = calculate_volume_cone(radius, height)
else:
print("Invalid shape choice. Please select a valid option (1/2/3/4).")
return

print(f"The {choice} of the selected shape is: {result}")

if __name__ == "__main__":
main()

SIMPLER CODE:-
import math

def sphere_area(radius):
return 4 * math.pi * radius ** 2

def sphere_volume(radius):
return (4/3) * math.pi * radius ** 3

def hemisphere_area(radius):
return 3 * math.pi * radius ** 2

def hemisphere_volume(radius):
return (2/3) * math.pi * radius ** 3

def cube_area(side):
return 6 * side ** 2

def cube_volume(side):
return side ** 3

def cone_area(radius, height):


slant_height = math.sqrt(radius ** 2 + height ** 2)
return math.pi * radius * (radius + slant_height)
def cone_volume(radius, height):
return (1/3) * math.pi * radius ** 2 * height

# User input
sphere_radius = float(input("Enter the radius of the sphere: "))
hemisphere_radius = float(input("Enter the radius of the hemisphere:
"))
cube_side = float(input("Enter the side length of the cube: "))
cone_radius = float(input("Enter the radius of the cone: "))
cone_height = float(input("Enter the height of the cone: "))

# Sphere calculations
print(f"Sphere Area: {sphere_area(sphere_radius)}")
print(f"Sphere Volume: {sphere_volume(sphere_radius)}\n")

# Hemisphere calculations
print(f"Hemisphere Area: {hemisphere_area(hemisphere_radius)}")
print(f"Hemisphere Volume:
{hemisphere_volume(hemisphere_radius)}\n")

# Cube calculations
print(f"Cube Area: {cube_area(cube_side)}")
print(f"Cube Volume: {cube_volume(cube_side)}\n")

# Cone calculations
print(f"Cone Area: {cone_area(cone_radius, cone_height)}")
print(f"Cone Volume: {cone_volume(cone_radius,
cone_height)}")

#7.
Write a python code to plot a graph of
speed . take input number as time, if initial
speed v0=10m/s ,calculate final speed .

CODE:-
import numpy as np
import matplotlib.pyplot as plt

# Given values
vo = 10 # Initial speed in m/s
g = 10 # Gravitational acceleration in m/s^2

# Generate an array of time values from 0 to 5 seconds (for example)


t = np.linspace(0, 5, 100) # Adjust the time range as needed

# Calculate the final speed using the equation v = vo + gt


v = vo + g * t

# Plot the graph of speed as a function of time


plt.plot(t, v, label=f'Speed (vo={vo} m/s, g={g} m/s^2)')
plt.xlabel('Time (s)')
plt.ylabel('Speed (m/s)')
plt.title('Speed vs. Time')
plt.grid()
plt.legend()
plt.show()

#8.
Write a python code to calculate time period
of a pendulum for 50 oscillations . take time
as input . (use formula: time taken/no. of
oscillations)

CODE:-
# Function to calculate time period for a given number of
oscillations
def calculate_time_period(total_time, num_oscillations):
time_period = total_time / num_oscillations
return time_period

# Taking input for total time taken for 50 oscillations


total_time_for_50_oscillations = float(input("Enter total time taken for 50
oscillations (in seconds): "))

# Number of oscillations (in this case, 50)


num_oscillations = 50

# Calculating the time period using the function


time_period = calculate_time_period(total_time_for_50_oscillations,
num_oscillations)

# Displaying the calculated time period


print(f"The time period for one oscillation is {time_period} seconds.")
#9.
Write a program that generates a series using
a function which takes 1st and last values of
series from user and then generates four
equidistant terms.

CODE:-

x=float(input("Enter the first value of series:"))


y=float(input("Enter the last value of serires:"))
def func(a,b):
print("-"*41,"\n")
print("Upper Limit : ",b,"\n")
print("Lower Limit : ",a,"\n")
d=(b-a)/3
print("The generated series is :",a,a+d,a+2*d,b,"\n",sep=" , ")
return "-"*41

print(func(x,y))
#10.
Take two lists, say for example these two: a = [1, 1, 2, 3, 5, 8, 13, 21,
34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] and write a
program that returns a list that contains only the elements that are
common between the lists (without duplicates). Make sure your
program works on two lists of different sizes. write this in one line of
python usinf atleast one list comprehension .

CODE:-

list1 = [1, 2, 3, 4, 5, 6]
list2 = [4, 5, 6, 7, 8, 9]

common_elements = list(set([x for x in list1 if x in


list2]))
print(“common_elements:”, common_elements)
#11.
Write a program to maintain employee details
like empno, name and salary using queues
data structure?(implement insert(), delete()
and traverse() function).
CODE(journal wala):-
from queue import Queue

class Employee:
def __init__(self, empno, name, salary):
self.empno = empno
self.name = name
self.salary = salary

def __str__(self):
return f"EmpNo: {self.empno}, Name: {self.name}, Salary:
{self.salary}"

class EmployeeQueue:
def __init__(self):
self.queue = Queue()
def insert(self, empno, name, salary):
employee = Employee(empno, name, salary)
self.queue.put(employee)
print(f"Employee {empno} added to the queue.")

def delete(self):
if not self.queue.empty():
deleted_employee = self.queue.get()
print(f"Employee {deleted_employee.empno} deleted from
the queue.")
else:
print("Queue is empty. Cannot delete.")

def traverse(self):
if not self.queue.empty():
print("Employee Details in the Queue:")
for employee in list(self.queue.queue):
print(employee)
else:
print("Queue is empty.")
CODE(working):-

import queue

class Employee:
def __init__(self, emp_no, name, salary):
self.emp_no = emp_no
self.name = name
self.salary = salary

def insert_employee(queue, emp_no, name, salary):


employee = Employee(emp_no, name, salary)
queue.put(employee)
print(f"Employee {emp_no} added successfully.")

def delete_employee(queue):
if not queue.empty():
removed_employee = queue.get()
print(f"Employee {removed_employee.emp_no} removed
successfully.")
else:
print("Queue is empty. No employee to remove.")

def traverse_employees(queue):
if not queue.empty():
print("Employee Details:")
for employee in list(queue.queue):
print(f"Emp No: {employee.emp_no}, Name:
{employee.name}, Salary: {employee.salary}")
else:
print("Queue is empty. No employee to display.")

# Example usage with user input


employee_queue = queue.Queue()

while True:
print("\n1. Insert Employee\n2. Delete Employee\n3. Traverse
Employees\n4. Quit")
choice = input("Enter your choice (1/2/3/4): ")

if choice == '1':
emp_no = int(input("Enter Employee Number: "))
name = input("Enter Employee Name: ")
salary = float(input("Enter Employee Salary: "))
insert_employee(employee_queue, emp_no, name, salary)
elif choice == '2':
delete_employee(employee_queue)
elif choice == '3':
traverse_employees(employee_queue)
elif choice == '4':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please enter a valid option.")
#12.
Write a python program to read a file named
“article.txt”, count and print total alphabets in the
file.

CODE(journal wala):-

def count_alpha():
lo = 0
with open("article.txt") as f:
while True:
c = f.read(1)
if not c:
break
print(c)
if ('A' <= c <= 'Z') or ('a' <= c <= 'z'):
lo = lo + 1
print("Total lower case alphabets: ", lo)

# function calling
count_alpha()
CODE (second option@ gpt):-

def count_alphabets(filename):
total_alphabets = 0

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


content = file.read()

for char in content:


if char.isalpha():
total_alphabets += 1

return total_alphabets

# Replace 'article.txt' with the actual path or name of your


file
file_path = 'article.txt'

result = count_alphabets(file_path)

print(f"Total number of alphabets in '{file_path}': {result}")


#13.
Write a function to insert a record in table
using python and mysql interface.

CODE:-
import mysql.connector

def insert_record():
# Replace these values with your MySQL database
connection details
db_config = {
'host': 'your_mysql_host',
'user': 'your_mysql_user',
'password': 'your_mysql_password',
'database': 'your_database_name',
}

try:
# Connect to the MySQL server
connection = mysql.connector.connect(**db_config)
# Create a cursor object to execute SQL queries
cursor = connection.cursor()

# Get user input for the record


name = input("Enter Name: ")
age = int(input("Enter Age: "))
salary = float(input("Enter Salary: "))

# Define the SQL query to insert a record into your table


insert_query = "INSERT INTO your_table_name (name,
age, salary) VALUES (%s, %s, %s)"

# Specify the values to be inserted


record_data = (name, age, salary)

# Execute the query


cursor.execute(insert_query, record_data)

# Commit the changes


connection.commit()
print("Record inserted successfully!")

except mysql.connector.Error as err:


print(f"Error: {err}")

finally:
# Close the cursor and connection
cursor.close()
connection.close()

# Example usage
insert_record()
#14.
Write a function to display all records stored
in a table using python and mysql interface.

CODE:-
import mysql.connector

def display_all():
# Connect to the MySQL server
db = mysql.connector.connect(host='localhost', user='root',
passwd='admin', database='test4')

try:
# Create a cursor object to execute SQL queries
c = db.cursor()

# Execute the SQL query


sql = 'SELECT * FROM student;'
c.execute(sql)

# Get the number of rows


countrow = c.rowcount
print("Number of rows: ", countrow)

# Fetch all the data


data = c.fetchall()

print("=========================")
print("Roll No Name Percentage")
print("=========================")
# Print each row of the result
for eachrow in data:
r, n, p = eachrow[0], eachrow[1], eachrow[2]
print(f"{r} {n} {p}")

print("=========================")

except mysql.connector.Error as err:


print(f"Error: {err}")
db.rollback()

finally:
# Close the cursor and connection
if 'db' in locals() and db.is_connected():
c.close()
db.close()

# Function calling
display_all()
#15.
Write a function to search a record stored in a
table using python and mysql interface.

CODE:-

import mysql.connector

def search_roll():
# Connect to the MySQL server
db = mysql.connector.connect(host="localhost", user="root",
passwd="admin", database="test")

try:
z=0
roll = int(input("Enter roll no to search: "))
c = db.cursor()
sql = 'SELECT * FROM student;'
c.execute(sql)
countrow = c.rowcount
print("Number of rows: ", countrow)
data = c.fetchall()
for eachrow in data:
r, n, p = eachrow[0], eachrow[1], eachrow[2]
if r == roll:
z=1
print("Roll No: {}, Name: {}, Percentage: {}".format(r, n, p))

if z == 0:
print("Record is not present")

except mysql.connector.Error as err:


print(f"Error: {err}")
db.rollback()

finally:
# Close the cursor and connection
if 'db' in locals() and db.is_connected():
c.close()
db.close()

# Function calling
search_roll()
#16.
Write a command in mysql to create a table.

CODE:-

CREATE TABLE EMPLOYEE

(EMPNO INTEGER PRIMARY KEY,

EMPNAME CHAR(20) NOT NULL,

JOB CHAR (25) NOT NULL,

MGR INTEGER,

HIREDATE DATE,

SAL DOUBLE CHECK (SAL>5000),

COMM REAL,

DEPTNO INTEGER);

INSERT INTO employee value (1008, “XYZ”, “CLERK”, 850, {23/12/2013}, 7500, 10, 5)

TABLE EMPLOYEE

EmpNo Emp Name Job Mgr HireDate Sal Com

7839 King President 07-Nov-81 5000

7782 Clark Manager 7839 09-Jun-81 2450


7566 Jones Manager 7839 02-April-81 2975

7499 Allen Salesman 7698 20-Feb-81 1600 300

7900 James Clerk 7698 03-Dec-81 950

# To show all the details from table employee

SELECT * from employee;

# To show specific column data from table employee

SELECT EMPNO, EMPNAME, SAL from employee;

# show those records where salary range from 5000 to 10000

SELECT * from employee where SAL >=5000 and SAL <= 10000;

# To show records whose name is BLAKE

SELECT * from employee whore EMPNAME = “BLAKE”;

You might also like