Program 20
Program 20
Program 20
Session:2014-15
REPORT FILE
COMPUTER SCIENCE
(PYTHON)
______________
H.O.D.’S SIGN
(MRS. KUMUD CHAUHAN)
___________________________________________________
________________
PRINCIPAL SIGN
(MR. DS. NEGI)
Ques.1 WAF to find weather a string is
PALINDROME or not.
defcount_vowels(s):
vowels = "aeiouAEIOU"
vowel_count = 0
for char in s:
if char in vowels:
vowel_count += 1
returnvowel_count
input_string = input("Enter a string:
")
vowels_in_string =
count_vowels(input_string)
print(f"The number of vowels in the
string is: {vowels_in_string}")
OUTPUT
Enter a string: PRIYANKA
The number of vowels in the string is: 1
OUTPUT
Enter the list of elements (comma-separated):
[3,646,46,44,66,4]
Enter the element to search: 646
The element '646' appears 1 time(s) at the following
index/indices: [1]
Ques.6 MAKE A MENU DRIVEN
PROGRAM USNING FUNCTION TO
ACCESS THEM.
1. AREA OF SQUARE
2. AREA OF CIRLCE
3. AREA OF RECTANGLE
4. PERIMETER OF SQUARE
PERIMETER OF CIRCLE
import math
defarea_of_square(side):
return side * side
defarea_of_circle(radius):
returnmath.pi * radius * radius
defarea_of_rectangle(length, breadth):
return length * breadth
defperimeter_of_square(side):
return 4 * side
defperimeter_of_circle(radius):
return 2 * math.pi * radius
def menu():
while True:
print("\nMenu:")
print("1. Area of Square")
print("2. Area of Circle")
print("3. Area of Rectangle")
print("4. Perimeter of Square")
print("5. Perimeter of Circle")
print("6. Exit")
choice = input("Enter your choice (1-6): ")
if choice == "1":
# Area of Square
side = float(input("Enter the side of the square:
"))
print(f"Area of Square: {area_of_square(side)}")
else:
print("Invalid choice! Please enter a number
between 1 and 6.")
OUTPUT
Menu:
1. Area of Square
2. Area of Circle
3. Area of Rectangle
4. Perimeter of Square
5. Perimeter of Circle
6. Exit
Enter your choice (1-6): 4
Enter the side of the square: 90
Perimeter of Square: 360.0
Menu:
1. Area of Square
2. Area of Circle
3. Area of Rectangle
4. Perimeter of Square
5. Perimeter of Circle
6. Exit
Enter your choice (1-6):
def modify_list(lst):
for i in range(len(lst)):
if lst[i] % 2 == 0:
lst[i] = lst[i] / 2
else:
lst[i] = lst[i] * 2
return lst
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
print("Original list:", my_list)
modified_list = modify_list(my_list)
print("Modified list:", modified_list)
OUTPUT
Original list: [1, 2, 3, 4, 5, 6, 7, 8]
Modified list: [2, 1.0, 6, 2.0, 10, 3.0, 14, 4.0]
Ques.8 Write a function namely nth root()
that receive two parameter x and n and
return nth root of x i.e. x1/n. the default value
of n is 2.
OUTPUT
The 4-th root of 16 is: 2.0
The square root of 16 is: 4.0
Ques.9 WAF to count and print lines
that start with "H" in file “Story.txt”.
def count_lines_starting_with_H(filename):
count = 0
try:
with open(filename, 'r') as file:
for line in file:
if line.strip().startswith('H'):
print(line.strip())
count += 1
print(f"\nTotal number of lines that start
with 'H': {count}")
except FileNotFoundError:
print(f"Error: The file '{filename}' was not
found.")
count_lines_starting_with_H('Story.txt')
OUTPUT
Assuming Story.txt contains the following:
Hello, this is a story.
How are you doing today?
This is another line.
Happiness is the key.
Habits form the future.
__________________________________________________
Hello, this is a story.
How are you doing today?
Happiness is the key.
Habits form the future.
Total number of lines that start with 'H':
if not record:
break
book_no, book_name, author_name,
price = struct.unpack('i50s50sf', record)
book_name =
book_name.decode('utf-8').strip()
author_name =
author_name.decode('utf-8').strip()
if author_name.lower() ==
author.lower():
count += 1
OUTPUT
Enter book number: 1
Enter book name: Python
Enter author name: XYZ
Enter book price: 290
import struct
def create_file():
with open("students.dat", "ab") as file:
roll_number = int(input("Enter roll
number: "))
name = input("Enter student name: ")
record = struct.pack('i50s',
roll_number, name.encode('utf-8'))
file.write(record)
print("Record added successfully!")
def search_by_roll_number(search_roll):
found = False
with open("students.dat", "rb") as file:
while True:
record =
file.read(struct.calcsize('i50s'))
if not record:
break
roll_number, name =
struct.unpack('i50s', record)
name = name.decode('utf-8').strip()
if roll_number == search_roll:
print(f"Roll Number:
{roll_number}, Name: {name}")
found = True
break
if not found:
print(f"Student with roll number
{search_roll} not found.")
if __name__ == "__main__":
while True:
create_file()
more = input("Do you want to add
another record? (y/n): ").lower()
if more != 'y':
break
try:
roll_number_to_search =
int(input("Enter roll number to search for: "))
search_by_roll_number(roll_number_to_sear
ch)
except ValueError:
print("Invalid input! Please enter a valid
roll number.")
OUTPUT
When adding records:
import struct
def display_avg_marks(sub):
total_marks = 0
count = 0
try:
with open("TEST.dat", "rb") as file:
while True:
record =
file.read(struct.calcsize('i50sii'))
break
test_id, subject, max_marks,
scored_marks = struct.unpack('i50sii',
record)
subject = subject.decode('utf-
8').strip()
if subject.lower() == sub.lower():
total_marks += scored_marks
count += 1
if count == 0:
print(f"No records found for the
subject: {sub}")
else:
avg_marks = total_marks / count
print(f"Average marks for the
subject '{sub}': {avg_marks:.2f}")
except FileNotFoundError:
print("Error: The file 'TEST.dat' was not
found.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
subject = input("Enter the subject to
calculate the average marks: ")
display_avg_marks(subject)
OUTPUT
Enter the subject to calculate the average
marks: Math
Average marks for the subject 'Math':
85.00
If no records found for the given subject:
def main():
my_dict = {"apple": 5, "banana": 10,
"cherry": 7}
if __name__ == "__main__":
main()
OUTPUT
Current dictionary: {'apple': 5, 'banana': 10,
'cherry': 7}
Enter the key to update or add: banana
Enter the new value for 'banana': 15
Value for key 'banana' updated to '15'.
Updated dictionary: {'apple': 5, 'banana': 15,
'cherry': 7}
def main():
text = "This is a sample text used to
demonstrate cursor movement functionality."
cursor_position = 0
if __name__ == "__main__":
main()
OUTPUT
Initial cursor position: 0
Cursor moved to position: 3
Next 5 characters from position 3: 's is '
Cursor moved to position: 13
Current cursor position: 13
Next 10 characters from position 13: 'mple
text '
Ques-15 Write a Python program to
implement a stack using list (PUSH &
POP Operation on Stack).
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
print(f"Pushed {item} to the stack")
def pop(self):
if not self.is_empty():
item = self.stack.pop()
print(f"Popped {item} from the
stack")
return item
else:
print("Stack is empty! Cannot
pop.")
return None
def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
print("Stack is empty! No top
element.")
return None
def is_empty(self):
return len(self.stack) == 0
def size(self):
return len(self.stack)
if __name__ == "__main__":
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
stack.pop()
print(f"Top element is: {stack.peek()}")
print(f"Is stack empty?
{stack.is_empty()}")
print(f"Stack size: {stack.size()}")
stack.pop()
stack.pop()
stack.pop()
OUTPUT
Pushed 10 to the stack
Pushed 20 to the stack
Pushed 30 to the stack
Top element is: 30
Popped 30 from the stack
Top element is: 20
Popped 20 from the stack
Popped 10 from the stack
Stack is empty! Cannot pop.
class Stack:
def __init__(self):
self.stack = []
def push(self, value):
"""Push an element onto the stack."""
self.stack.append(value)
def pop(self):
"""Pop an element from the stack."""
if not self.is_empty():
return self.stack.pop()
else:
return None
def is_empty(self):
"""Check if the stack is empty."""
return len(self.stack) == 0
def display(self):
"""Display the contents of the stack."""
if self.is_empty():
print("Stack is empty.")
else:
print("Stack contents:", self.stack)
def push_prices_to_stack(product_dict, stack):
"""Push product prices greater than 300 into
the stack."""
for product, price in product_dict.items():
if price > 300:
stack.push(price)
print(f"Pushed {price} to the stack")
def pop_stack_contents(stack):
"""Pop and display contents of the stack."""
print("Popping from stack:")
while not stack.is_empty():
value = stack.pop()
print(f"Popped {value} from the stack")
if __name__ == "__main__":
product = {'Book': 250, 'Pen': 120, 'Pencil': 50,
'Notebook': 400, 'Register': 480}
stack = Stack()
push_prices_to_stack(product, stack)
stack.display()
pop_stack_contents(stack)
OUTPUT
Pushed 400 to the stack
Pushed 480 to the stack
Stack contents: [400, 480]
Popping from stack:
Popped 480 from the stack
Popped 400 from the stack
def POP(Arr):
"""Pop the top element from the stack and
return it."""
if len(Arr) > 0:
return Arr.pop()
else:
print("Stack is empty! Cannot pop.")
return None
if __name__ == "__main__":
stack = [10, 20, 30, 40, 50]
print("Initial stack:", stack)
print("Popped value:", POP(stack))
print("Updated stack:", stack)
print("Popped value:", POP(stack))
print("Updated stack:", stack)
OUTPUT
Initial stack: [10, 20, 30, 40, 50]
Popped value: 50
Updated stack: [10, 20, 30, 40]
Popped value: 40
Updated stack: [10, 20, 30]
Stack is empty! Cannot pop.
Popped value: None
Ques-18 Prateek has created a list arr with
some elements. Help him to create a user-
defined function to perform the following tasks:
*Create a stack after checking the elements if
it is even then multiply by 2 and if the element
is odd ,then multiply it by 3.
* Pop and display the contents of the stack.
def create_stack(arr):
"""Create a stack based on the given list,
modifying elements as per the conditions."""
stack = []
for num in arr:
if num % 2 == 0:
stack.append(num * 2)
else:
stack.append(num * 3)
return stack
def pop_and_display_stack(stack):
"""Pop and display the contents of the
stack."""
print("Popping from the stack:")
while stack:
popped_value = stack.pop()
print(f"Popped {popped_value} from the
stack")
if not stack:
print("Stack is empty!")
if __name__ == "__main__":
arr = [10, 15, 8, 9, 3, 12, 5]
stack = create_stack(arr)
print("Created stack:", stack)
pop_and_display_stack(stack)
OUTPUT
Created stack: [20, 45, 16, 27, 9, 24, 15]
Popping from the stack:
Popped 15 from the stack
Popped 24 from the stack
Popped 9 from the stack
Popped 27 from the stack
Popped 16 from the stack
Popped 45 from the stack
Popped 20 from the stack
Stack is empty!
Ques-19 Integrate MySQL with Python by
importing the MySQL module and add records of
student and display all the record.
import mysql.connector
def connect_to_database():
"""Establish a connection to the MySQL database."""
try:
connection = mysql.connector.connect(
host='localhost',
user='root',
password='password',
database='school' )
if connection.is_connected():
print("Successfully connected to the database.")
return connection
except mysql.connector.Error as err:
print(f"Error: {err}")
return None
def add_student(connection, name, age, grade):
"""Add a student record to the students table."""
cursor = connection.cursor()
insert_query = "INSERT INTO students (name, age,
grade) VALUES (%s, %s, %s)"
values = (name, age, grade)
try:
cursor.execute(insert_query, values)
connection.commit()
print(f"Student '{name}' added successfully.")
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
cursor.close()
def display_students(connection):
"""Display all student records from the students
table."""
cursor = connection.cursor()
select_query = "SELECT * FROM students"
try:
cursor.execute(select_query)
records = cursor.fetchall()
print("\nStudent Records:")
print("ID | Name | Age | Grade")
print("-" * 30)
for row in records:
print(f"{row[0]} | {row[1]} | {row[2]} | {row[3]}")
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
cursor.close()
if __name__ == "__main__":
connection = connect_to_database()
if connection:
add_student(connection, 'RAM', 20, 'A')
add_student(connection, 'SHYAM', 22, 'B')
add_student(connection, 'SANCHI', 21, 'A')
display_students(connection)
connection.close()
OUTPUT
Successfully connected to the database.
Student 'RAM' added successfully.
Student 'SHYAM' added successfully.
Student 'SANCHI' added successfully.
Student Records:
ID | Name | Age | Grade
--------------------------------------------------------------
1 | RAM | 20 | A
2 | SHYAM | 22 | B
3 | SANCHI | 21 | A
Ques-20 Integrate SQL with Python by
importing the MySQL module to search a
student using rollno, update the record.
Python Program:
import mysql.connector
def connect_to_database():
"""Establish a connection to the MySQL database."""
try:
connection = mysql.connector.connect(
host='localhost',
user='root',
password='password'
database='school')
if connection.is_connected():
print("Successfully connected to the database.")
return connection
except mysql.connector.Error as err:
print(f"Error: {err}")
return None
def search_student_by_rollno(connection, rollno):
"""Search for a student by roll number."""
cursor = connection.cursor()
select_query = "SELECT * FROM students WHERE rollno = %s"
try:
cursor.execute(select_query, (rollno,))
result = cursor.fetchone()
if result:
print(f"Student Found: Roll No: {result[0]}, Name: {result[1]}, Age:
{result[2]}, Grade: {result[3]}")
return result
else:
print(f"No student found with Roll No: {rollno}")
return None
except mysql.connector.Error as err:
print(f"Error: {err}")
return None
finally:
cursor.close()
def update_student_record(connection, rollno, new_name, new_age,
new_grade):
"""Update student record based on roll number."""
cursor = connection.cursor()
update_query = "UPDATE students SET name = %s, age = %s,
grade = %s WHERE rollno = %s"
values = (new_name, new_age, new_grade, rollno)
try:
cursor.execute(update_query, values)
connection.commit() # Commit the changes to the database
if cursor.rowcount > 0:
print(f"Student record with Roll No {rollno} updated successfully.")
else:
print(f"No record found with Roll No {rollno} to update.")
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
cursor.close()
if __name__ == "__main__":
connection = connect_to_database()
if connection:
rollno = int(input("Enter the roll number of the student to search: "))
student = search_student_by_rollno(connection, rollno)
if student:
new_name = input(f"Enter new name for {student[1]}: ")
new_age = int(input(f"Enter new age for {student[1]}: "))
new_grade = input(f"Enter new grade for {student[1]}: ")
update_student_record(connection, rollno, new_name, new_age,
new_grade)
connection.close()
OUTPUT
Successfully connected to the database.
Enter the roll number of the student to search: 1
Student Found: Roll No: 1, Name: Alice, Age: 20, Grade: A
Enter new name for Alice: Alicia
Enter new age for Alicia: 21
Enter new grade for Alicia: B
Student record with Roll No 1 updated successfully .
Ques-21 20 SQL QUERRIES .
1. Create a Table
Create a table called students with columns for student_id, name, age, and
grade.
2. Insert Data
Select the name and age columns from the students table.
6. Update Data
7. Delete Data
8. Count Records
9. Order By
10. Group By
Suppose there are two tables: students and courses (with columns course_id,
student_id, course_name). Select the student name and their course name.
Select all students and their courses, including students who may not
have enrolled in any courses.
Select all courses and the students who are enrolled in them.
15. Union
Combine the results of two SELECT queries (e.g., students from two
different courses).
Let's explore SQL Aggregate Functions and SQL JOINs with examples.
Example Database
2.1 INNER JOIN – Join students and courses tables on student_id and select
students with their course names:
Result:
| name | course_name |
|---------|-------------|
| Alice | Math |
| Alice | Science |
| Bob | Math |
| Charlie | History |
| David | Math |
2.2 LEFT JOIN – List all students and their courses, including students who are not
enrolled in any courses:
Result:
| name | course_name |
|---------|-------------|
| Alice | Math |
| Alice | Science |
| Bob | Math |
| Charlie | History |
| David | Math |
2.3 RIGHT JOIN – List all courses and the students enrolled in them:
Result:
javascript
Copy code
| name | course_name |
|---------|-------------|
| Alice | Math |
| Alice | Science |
| Bob | Math |
| Charlie | History |
| David | Math |
2.4 FULL JOIN (Not supported in MySQL) – A full join would combine the results of
LEFT JOIN and RIGHT JOIN by including all rows from both tables. However, MySQL
doesn't support FULL JOIN directly, so it can be achieved by combining LEFT JOIN and
RIGHT JOIN using UNION.
2.5 SELF JOIN – A self join is a join of a table with itself. For example, suppose you
want to find students who have the same grade as another student:
3.1 COUNT with JOIN – Count the number of courses each student is enrolled in:
Result:
| name | course_count |
|---------|--------------|
| Alice | 2 |
| Bob | 1 |
| Charlie | 1 |
| David | 1 |
3.2 AVG with JOIN – Calculate the average age of students enrolled in each course:
Result:
| course_name | average_age |
|-------------|-------------|
| Math | 21 |
| Science | 20 |
| History | 21 |