Professional Documents
Culture Documents
Code:-
# taking input from user
number = int(input("Enter any number: "))
CODE:-
def multiply_until_24998(number):
result = number
count = 1
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
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
# Generate x values
x = np.linspace(-2 * np.pi, 2 * np.pi, 1000) # Adjust the range as needed
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 main():
print("Calculate Area or Volume?")
choice = input("Enter 'area' or 'volume': ").lower()
print("Select a shape:")
print("1. Sphere")
print("2. Hemisphere")
print("3. Cube")
print("4. Cone")
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
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
# 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
#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
CODE:-
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]
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 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.")
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
return total_alphabets
result = count_alphabets(file_path)
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()
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()
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("=========================")
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")
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:-
MGR INTEGER,
HIREDATE DATE,
COMM REAL,
DEPTNO INTEGER);
INSERT INTO employee value (1008, “XYZ”, “CLERK”, 850, {23/12/2013}, 7500, 10, 5)
TABLE EMPLOYEE
SELECT * from employee where SAL >=5000 and SAL <= 10000;