1.Write a program to calculate the factorial of the given number using for loop.
Code:-
num= int(input("enter the number:"))
f=1
if num==0:
print("the factorial of",num,"is",1)
else:
for i in range(num,0,-1):
f=f*i
print("the factorial of",num,"is",f)
output:-
>>>enter the number:5
the factorial of 5 is 120
>>>enter the number:54
the factorial of 54 is
230843697339241380472092742683027581083278564571807941132288000000000000
>>> enter the number:9
the factorial of 9 is 362880
2.Write a program to check whether an entered number is Armstrong or not.
Code-
a=(input("enter the number:"))
l=len(a)
n=l
b=0
while l>0:
c=int(a[l-1])
d=c**n
l=l-1
b=b+d
if int(a)==b:
print("the number",a,"is armstrong")
else:
print("the number",a,"is not armstrong")
output-
>>>enter the number:312
the number 312 is not armstrong
>>>enter the number:1
the number 1 is armstrong
>>>enter the number:456
the number 456 is not armstrong
3. Write a program to create a mirror of the given string. For example, “arm” = “mra“.
Code-
a=input("enter the string:")
l=len(a)
print("the mirror image is \n",a,"= ",end="")
for i in range(l-1,-1,-1):
print(a[i],end="")
output:-
enter the string:hello
the mirror image is
hello = olleh
enter the string:hello
the mirror image is
hello = olleh
. Generate values from 1 to 10 and remove odd numbers
python
Copy code
# Generate values and remove odd numbers
numbers = list(range(1, 11))
even_numbers = [num for num in numbers if num % 2 == 0]
print("Even numbers:", even_numbers)
Output:
less
Copy code
Even numbers: [2, 4, 6, 8, 10]
Create a simple calculator using functions
python
Copy code
def calculator(a, b, operation):
if operation == "add":
return a + b
elif operation == "subtract":
return a - b
elif operation == "multiply":
return a * b
elif operation == "divide":
return a / b if b != 0 else "Cannot divide by zero"
else:
return "Invalid operation"
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
operation = input("Enter operation (add/subtract/multiply/divide): ")
print("Result:", calculator(a, b, operation))
3. Calculate total marks and filter by vowels
python
Copy code
def calculate(data):
for name, marks in data.items():
if name[0].lower() in 'aeiou':
total = sum(marks)
print(f"Name: {name}, Total Marks: {total}")
students = {
"Agam": [30, 25, 24, 30],
"Garv": [21, 25, 26, 30],
"Eknoor": [33, 27, 24, 30]
calculate(students)
Check if a character exists in a string
python
Copy code
def check_char(string, char):
for c in string:
if c == char:
return True
return False
string = input("Enter a string: ")
char = input("Enter a character to check: ")
print("Character found:", check_char(string, char))
5. Check and count vowels
python
Copy code
def count_vowels(string):
vowels = "aeiou"
count = 0
for char in string.lower():
if char in vowels:
count += 1
return count
string = input("Enter a string: ")
count = count_vowels(string)
if count > 0:
print(f"Number of vowels: {count}")
else:
print("No vowels found")
6. Dice simulator
python
Copy code
import random
def roll_dice():
return random.randint(1, 6)
print("Dice roll result:", roll_dice())
7. Stack using list
python
Copy code
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
if not self.is_empty():
return self.stack.pop()
return "Stack Empty"
def is_empty(self):
return len(self.stack) == 0
# Testing
s = Stack()
s.push(10)
s.push(20)
print(s.pop()) # 20
print(s.pop()) # 10
print(s.pop()) # Stack Empty
11. SQL: Employee table creation
sql
Copy code
CREATE TABLE Employee (
Empno INT PRIMARY KEY,
Empname VARCHAR(50),
Desig VARCHAR(50),
Dept VARCHAR(50),
Age INT,
Place VARCHAR(50)
);
INSERT INTO Employee VALUES
(1, 'John', 'Manager', 'HR', 40, 'Delhi'),
(2, 'Sara', 'Analyst', 'IT', 32, 'Mumbai'),
(3, 'Raj', 'Clerk', 'Admin', 25, 'Chennai'),
(4, 'Priya', 'Developer', 'IT', 28, 'Bangalore'),
(5, 'Karan', 'Executive', 'Sales', 29, 'Kolkata');
-- Add more records
INSERT INTO Employee VALUES (6, 'Neha', 'Tester', 'QA', 27, 'Hyderabad');
INSERT INTO Employee VALUES (7, 'Anil', 'Consultant', 'Finance', 35, 'Pune');
-- Add new column
ALTER TABLE Employee ADD doj DATE;
-- Update DOJ values
UPDATE Employee SET doj = '2023-01-15' WHERE Empno = 1;
-- Employees who joined after 2023/01/01
SELECT * FROM Employee WHERE doj > '2023-01-01';
12. SQL Commands for Primary Key, Foreign Key, and Check Constraints
sql
Copy code
-- Creating tables with constraints
CREATE TABLE Department (
DeptID INT PRIMARY KEY,
DeptName VARCHAR(50)
);
CREATE TABLE Employee (
EmpID INT PRIMARY KEY,
EmpName VARCHAR(50),
Age INT CHECK (Age > 18),
DeptID INT,
FOREIGN KEY (DeptID) REFERENCES Department(DeptID)
);
13. SQL Commands to Demonstrate Joins
sql
Copy code
-- Inner Join
SELECT Employee.EmpName, Department.DeptName
FROM Employee
INNER JOIN Department ON Employee.DeptID = Department.DeptID;
-- Left Join
SELECT Employee.EmpName, Department.DeptName
FROM Employee
LEFT JOIN Department ON Employee.DeptID = Department.DeptID;
-- Right Join
SELECT Employee.EmpName, Department.DeptName
FROM Employee
RIGHT JOIN Department ON Employee.DeptID = Department.DeptID;
14. SQL Commands to Use Group By, Order By, and Having
sql
Copy code
-- Group By and Order By with Having
SELECT DeptID, COUNT(*) AS EmployeeCount
FROM Employee
GROUP BY DeptID
HAVING COUNT(*) > 1
ORDER BY EmployeeCount DESC;
15. SQL Commands for Aggregate Functions
sql
Copy code
SELECT COUNT(*) AS TotalEmployees FROM Employee;
SELECT AVG(Age) AS AverageAge FROM Employee;
SELECT MAX(Age) AS MaxAge FROM Employee;
SELECT MIN(Age) AS MinAge FROM Employee;
SELECT SUM(Age) AS TotalAge FROM Employee;
16. Fetch a Record Using Python and SQL
python
Copy code
import sqlite3
conn = sqlite3.connect('company.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM Employee WHERE EmpID = ?", (1,))
record = cursor.fetchone()
print("Record:", record)
conn.close()
17. Update a Record Using Python and SQL
python
Copy code
import sqlite3
conn = sqlite3.connect('company.db')
cursor = conn.cursor()
cursor.execute("UPDATE Employee SET Age = ? WHERE EmpID = ?", (35, 1))
conn.commit()
print("Record Updated")
conn.close()
18. Delete a Record Using Python and SQL
python
Copy code
import sqlite3
conn = sqlite3.connect('company.db')
cursor = conn.cursor()
cursor.execute("DELETE FROM Employee WHERE EmpID = ?", (1,))
conn.commit()
print("Record Deleted")
conn.close()
19. Operations on Travel Stack
python
Copy code
def push_element(travel_stack, nlist):
for record in nlist:
city, country, distance = record
if country != "India" and distance < 3500:
travel_stack.append([city, country])
def pop_element(travel_stack):
if travel_stack:
return travel_stack.pop()
return "Stack Empty"
# Example Usage
travel_stack = []
nlist = [
["Paris", "France", 4000],
["Kathmandu", "Nepal", 1200],
["Tokyo", "Japan", 6000],
["Dubai", "UAE", 3400]
push_element(travel_stack, nlist)
print(pop_element(travel_stack)) # ["Dubai", "UAE"]
print(pop_element(travel_stack)) # ["Kathmandu", "Nepal"]
print(pop_element(travel_stack)) # Stack Empty
20. Push Employee Data into Stack
python
Copy code
def push_data(payroll, emp_dict):
for emp, salary in emp_dict.items():
if salary > 40000:
payroll.append(emp)
# Example Usage
payroll = []
employees = {"John": 45000, "Sara": 39000, "Mike": 50000}
push_data(payroll, employees)
print(payroll) # ['John', 'Mike']
21. Pop Data from Stack
python
Copy code
def pop_data(payroll):
while payroll:
print(payroll.pop())
print("Stack underflow")
# Example Usage
pop_data(payroll) # Mike, John, Stack underflow
22. Write Data to Binary File
python
Copy code
import pickle
def write_bin(emp_list):
with open("employees.dat", "wb") as file:
for emp in emp_list:
if emp[1] > 40:
pickle.dump(emp, file)
# Example Usage
employees = [("John", 45, "New York"), ("Sara", 30, "Delhi"), ("Mike", 50, "Paris")]
write_bin(employees)
23. Write Data to CSV File
python
Copy code
import csv
def write_csv(student_records):
with open("result.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Class", "Marks"])
for record in student_records:
if record[2] < 50:
writer.writerow(record)
# Example Usage
students = [("Alice", 10, 45), ("Bob", 11, 60), ("Charlie", 12, 30)]
write_csv(students)
24. Count Lines in CSV
python
Copy code
def count_csv():
with open("result.csv", "r") as file:
return sum(1 for _ in file)
print("Lines in CSV:", count_csv())
25. Filter Data from Binary File
python
Copy code
import pickle
def filter_bin():
try:
with open("employees.dat", "rb") as file:
found = False
while True:
try:
record = pickle.load(file)
if record[0].startswith("S"):
print(record)
found = True
except EOFError:
break
if not found:
print("Not available")
except FileNotFoundError:
print("File not found")
filter_bin()