0% found this document useful (0 votes)
26 views3 pages

Class 12 Python Advanced Programs

The document contains a collection of advanced Python programs for Class 12, including a menu-driven calculator, GCD calculation using recursion, binary search, bubble sort, file handling for counting lines/words/characters, and searching for words. It also covers CSV file operations, data structures like stacks and queues, object-oriented programming with classes and inheritance, exception handling, prime number checking, list comprehensions, and random password generation. Each program is presented with code snippets and brief explanations of their functionality.

Uploaded by

dhullgagan482
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views3 pages

Class 12 Python Advanced Programs

The document contains a collection of advanced Python programs for Class 12, including a menu-driven calculator, GCD calculation using recursion, binary search, bubble sort, file handling for counting lines/words/characters, and searching for words. It also covers CSV file operations, data structures like stacks and queues, object-oriented programming with classes and inheritance, exception handling, prime number checking, list comprehensions, and random password generation. Each program is presented with code snippets and brief explanations of their functionality.

Uploaded by

dhullgagan482
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Class 12 – Python Practical File (Advanced

Programs)

1. Menu Driven Calculator Using Functions


def add(a, b): return a + b
def sub(a, b): return a - b
def mul(a, b): return a * b
def div(a, b): return a / b if b != 0 else "Division by zero"

while True:
print("[Link] [Link] [Link] [Link] [Link]")
ch = int(input("Enter choice: "))
if ch == 5:
break
a, b = int(input("A: ")), int(input("B: "))
print([add, sub, mul, div][ch-1](a, b))

2. GCD Using Recursion


def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)

print(gcd(48, 18))

3. Binary Search
def binary_search(lst, key):
low, high = 0, len(lst)-1
while low <= high:
mid = (low + high)//2
if lst[mid] == key:
return mid
elif lst[mid] < key:
low = mid + 1
else:
high = mid - 1
return -1

lst = [10, 20, 30, 40, 50]


print(binary_search(lst, 30))

4. Bubble Sort
lst = [5, 1, 4, 2, 8]
for i in range(len(lst)):
for j in range(len(lst)-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
print(lst)

5. File Handling – Count Lines, Words, Characters


with open("[Link]", "r") as f:
text = [Link]()
print("Lines:", [Link]('\n')+1)
print("Words:", len([Link]()))
print("Characters:", len(text))

6. File Handling – Search Word


word = input("Enter word: ")
with open("[Link]") as f:
if word in [Link]():
print("Word found")
else:
print("Word not found")

7. CSV – Write Student Records


import csv
with open("[Link]", "w", newline="") as f:
writer = [Link](f)
[Link](["Roll", "Name", "Marks"])
[Link]([1, "Aman", 89])

8. CSV – Read Records


import csv
with open("[Link]") as f:
reader = [Link](f)
for row in reader:
print(row)

9. Dictionary – Student Result


students = {"Aman": 89, "Riya": 92, "Karan": 76}
name = input("Enter name: ")
print("Marks:", [Link](name, "Not found"))

10. Stack Using List


stack = []
[Link](10)
[Link](20)
print([Link]())
print(stack)

11. Queue Using List


queue = []
[Link](1)
[Link](2)
print([Link](0))
print(queue)

12. OOP – Student Class


class Student:
def __init__(self, name, marks):
[Link] = name
[Link] = marks

def display(self):
print([Link], [Link])

s1 = Student("Aman", 90)
[Link]()

13. Inheritance Example


class Person:
def show(self):
print("I am a person")

class Student(Person):
def show_student(self):
print("I am a student")
s = Student()
[Link]()
s.show_student()

14. Exception Handling


try:
a = int(input("Enter number: "))
print(10 / a)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid input")

15. Prime Number Check


def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True

print(is_prime(17))

16. List Comprehension


squares = [x*x for x in range(1, 11)]
print(squares)

17. Tuple Max & Min


t = (5, 12, 7, 3)
print("Max:", max(t))
print("Min:", min(t))

18. Palindrome Check


s = input("Enter string: ")
print("Palindrome" if s == s[::-1] else "Not Palindrome")

19. Random Password Generator


import random, string
password = ''.join([Link](string.ascii_letters + [Link], k=8))
print(password)

20. File Copy Program


with open("[Link]") as f1, open("[Link]", "w") as f2:
[Link]([Link]())

Common questions

Powered by AI

Anonymous functions, or lambdas, improve Python's functionality by allowing concise expression of simple functions, especially valuable in data processing tasks such as sorting, filtering, or mapping sequences. For instance, using 'sorted(lst, key=lambda x: x[1])' can easily sort a list of tuples by the second element without defining a separate function. Lambdas enhance functionality where a small, unnamed function is required, promoting greater flexibility and readability in code involving functional programming patterns like map, filter, and reduce, simplifying tasks requiring simple operations applied across data sets .

Inheritance in object-oriented programming allows one class to inherit attributes and methods from another, promoting code reusability and logical hierarchy. In the 'Person' and 'Student' classes example, the 'Student' class inherits from the 'Person' class, meaning 'Student' objects can access methods defined in 'Person', like 'show', along with its own methods like 'show_student'. This implements the concept of the 'is-a' relationship, where 'Student' is a specialized type of 'Person' . Such an approach reduces redundancy and enhances maintainability by allowing shared behavior while enabling extension of functionality.

File operations in Python are optimized by abstracting low-level file handling through built-in functions like 'open', which manage resources efficiently by using context managers to ensure files are properly opened and closed. This reduces the risk of file corruption or data loss . A potential pitfall is failing to handle exceptions that might occur, such as FileNotFoundError or IOError, leading to unanticipated crashes. Best practices include using 'with' statements for automatic file closure, implementing exception handling mechanisms, validating file paths, and ensuring correct file modes to enhance error resilience and data integrity.

List comprehensions offer a concise and readable way to generate lists, such as a list of squares. Using a list comprehension, squares can be generated with '[x*x for x in range(1, 11)]', which is more compact than using a traditional 'for' loop with an 'append' statement . The advantages include shorter, more readable code and often better performance due to the optimized internals of comprehensions. However, they can be less intuitive for complex operations than loops, limiting readability and debugging, especially for those unfamiliar with comprehensions.

Using mutable data structures like lists for implementing queues in Python allows dynamic resizing, which makes them flexible for varying numbers of elements. Lists facilitate easy append operations, but removing elements from the front (queue dequeue operation) involves shifting elements, leading to an average time complexity of O(n). This impacts performance with larger datasets, as the operation becomes less efficient compared to implementing queues with collections.deque, which offers O(1) operations for appending and popping elements at either end. Therefore, while lists provide simple usability, they may not yield the best performance.

The Student class demonstrates object-oriented principles by encapsulating data and methods related to a student within a single entity. It contains attributes like 'name' and 'marks' and a method 'display' to output these attributes, illustrating encapsulation and data abstraction . This organization allows for easy management of student-related data and operations, promoting code reuse and modularity. Changes to student-related processes are confined to the class, reducing the impact on the rest of the code and supporting maintainability and scalability.

Exception handling in the division operation program prevents runtime errors by catching exceptions such as ZeroDivisionError and ValueError. By encapsulating the division operation in a try block, the program can manage errors without crashing. It mitigates potential issues like performing division by zero, which would result in an undefined operation, as well as handling invalid user inputs that cannot be converted to integers . This results in more robust code, allowing the program to gracefully inform users of their mistakes without terminating unexpectedly.

To modify a stack implemented using a list to include error handling for pop operations on an empty stack, you can incorporate a try-except block. Before performing the pop operation, check if the stack is empty using an 'if' statement. If it is empty, raise an IndexError or return a custom error message. Encapsulate the pop call within a try block and catch potential exceptions, providing feedback to the user that the stack is empty. This ensures robustness by preventing runtime errors during invalid operations .

Recursion in calculating the GCD involves repeatedly applying the Euclidean algorithm, which is based on the principle that the GCD of two numbers also divides their difference. The recursive function 'gcd(a, b)' in Python checks if 'b' equals zero, in which case it returns 'a' as the GCD. Otherwise, it calls itself with 'b' and 'a % b' as new parameters, effectively reducing the problem size with each call . This recursive approach simplifies the code, making it more readable and maintaining clarity in the algorithm's logic, compared to iterative methods which involve explicit loops and extra variables.

Binary search is efficient on a sorted list because it follows a divide-and-conquer approach, reducing the search space by half with each iteration, resulting in a time complexity of O(log n). The key operation is comparing the midpoint with the target value, allowing the algorithm to discard half of the list at each step . In an unsorted list, binary search does not work effectively because the midpoint does not confer any guarantee about which half contains the target. Thus, sorting is a prerequisite to ensure that comparisons at each stage provide meaningful guidance to discard half the search space.

You might also like