Python Fundamentals for Class 12 CS
Cheatsheet Content
Basic Operations 1. Square and Cube of a Number a = int(input("Enter any no ")) b = a * a c = a * a * a print("Square = ", b) print("cube = ", c) 2. Sum, Product, and Difference of Two Numbers a = int(input("Enter 1st no ")) b = int(input("Enter 2nd no ")) s = a + b p = a * b d = abs(a - b) # Using abs() for difference print("Sum = ", s) print("Product = ", p) print("Difference = ", d) 3. Largest of Three Numbers Method 1 (Nested if-else): a = int(input("Enter 1st no ")) b = int(input("Enter 2nd no ")) c = int(input("Enter 3rd no ")) if (a > b and a > c): m = a else: if (b > c): m = b else: m = c print("Max no = ", m) Method 2 (elif): num1 = int(input("Enter 1st no ")) num2 = int(input("Enter 2nd no ")) num3 = int(input("Enter 3rd no ")) if (num1 > num2 and num1 > num3): max_num = num1 elif (num2 > num3): max_num = num2 else: max_num = num3 print("Max no = ", max_num) 4. Simple Calculator a = int(input("Enter 1st no ")) b = int(input("Enter 2nd no ")) op = input("Enter the operator (+,-,*,/) ") if (op == "+"): c = a + b print("Sum = ", c) elif (op == "*"): c = a * b print("Product = ", c) elif (op == "-"): c = abs(a - b) print("Difference = ", c) elif (op == "/"): if b != 0: c = a / b print("Division = ", c) else: print("Error: Division by zero") else: print("Invalid operator") Loops and Series 5. Multiplication Table num = int(input("Enter any no ")) i = 1 while (i 6. Factorial (Iterative) n = int(input("Enter any no ")) i = 1 f = 1 while (i 7. Armstrong Number Check n = int(input("Enter the number to check : ")) n1 = n s = 0 while (n > 0): d = n % 10 s = s + (d * d * d) n = int(n / 10) if s == n1: print("Armstrong Number") else: print("Not an Armstrong Number") 8. Factorial (Recursive) def recur_factorial(n): if n == 1: return n else: return n * recur_factorial(n - 1) num = int(input("Enter any no ")) if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: print("The factorial of", num, "is", recur_factorial(num)) 9. Fibonacci Sequence (Recursive) def recur_fibo(n): if n <= 1: return n else: return (recur_fibo(n - 1) + recur_fibo(n - 2)) nterms = int(input("Enter upto which term you want to print: ")) if (nterms <= 0): print("Please enter a positive integer") else: print("Fibonacci sequence:") for i in range(nterms): print(recur_fibo(i)) Data Structures 10. Stack Implementation (Books) book = [] def push(): bcode = input("Enter bcode ") btitle = input("Enter btitle ") price = input("Enter price ") bk = (bcode, btitle, price) book.append(bk) def pop_item(): # Renamed to avoid clash with built-in pop() if (not book): # Check if stack is empty print("Underflow / Book Stack is empty") else: bcode, btitle, price = book.pop() print("Popped element is:") print("bcode ", bcode, " btitle ", btitle, " price ", price) def traverse(): if (not book): # Check if stack is empty print("Empty, No book to display") else: n = len(book) for i in range(n - 1, -1, -1): # Display from top to bottom print(book[i]) while True: print("\n1. Push") print("2. Pop") print("3. Traversal") print("4. Exit") ch = int(input("Enter your choice ")) if (ch == 1): push() elif (ch == 2): pop_item() elif (ch == 3): traverse() elif (ch == 4): print("End") break else: print("Invalid choice") 11. Queue Implementation (Employees) employee = [] def add_element(): empno = input("Enter empno ") name = input("Enter name ") sal = input("Enter sal ") emp = (empno, name, sal) employee.append(emp) def del_element(): if (not employee): # Check if queue is empty print("Underflow / Employee Queue is empty") else: empno, name, sal = employee.pop(0) print("Dequeued element is:") print("empno ", empno, " name ", name, " salary ", sal) def traverse_queue(): # Renamed to avoid clash if (not employee): # Check if queue is empty print("Empty, No employee to display") else: for emp_data in employee: print(emp_data) while True: print("\n1. Add employee") print("2. Delete employee") print("3. Traversal") print("4. Exit") ch = int(input("Enter your choice ")) if (ch == 1): add_element() elif (ch == 2): del_element() elif (ch == 3): traverse_queue() elif (ch == 4): print("End") break else: print("Invalid choice") File Handling 12. Count Alphabets in File def count_alpha(): total_alphabets = 0 try: with open("article.txt", "r") as f: while True: c = f.read(1) if not c: break # print(c) # Uncomment to see characters being read if c.isalpha(): total_alphabets += 1 print("Total alphabets: ", total_alphabets) except FileNotFoundError: print("Error: 'article.txt' not found.") count_alpha() 13. File Analysis (Characters, Digits, Spaces) def analyze_file(): total_chars = 0 total_alphabets = 0 upper_alphabets = 0 lower_alphabets = 0 total_digits = 0 total_spaces = 0 special_chars = 0 # Non-alphanumeric, non-space try: with open("article.txt", "r") as f: while True: c = f.read(1) if not c: break total_chars += 1 if c.isalpha(): total_alphabets += 1 if c.isupper(): upper_alphabets += 1 else: lower_alphabets += 1 elif c.isdigit(): total_digits += 1 elif c.isspace(): # Includes ' ', '\n', '\t' total_spaces += 1 else: special_chars += 1 print("Total characters (length of file):", total_chars) print("Total alphabets:", total_alphabets) print("Total upper case alphabets:", upper_alphabets) print("Total lower case alphabets:", lower_alphabets) print("Total digits:", total_digits) print("Total spaces (including newlines):", total_spaces) print("Total special characters:", special_chars) except FileNotFoundError: print("Error: 'article.txt' not found.") analyze_file() 14. Count Words Starting with 'a' or 'A' def count_words_starting_with_a(): count = 0 try: with open("article.txt", "r") as f: for line in f: for word in line.split(): if word and (word[0] == "a" or word[0] == "A"): print(word) count += 1 print("Total words starting with 'a' or 'A':", count) except FileNotFoundError: print("Error: 'article.txt' not found.") count_words_starting_with_a() 15. Count Lines Starting with Vowels def count_vowel_start_lines(): filepath = 'article.txt' vowels = "AEIOUaeiou" line_count = 0 try: with open(filepath, "r") as fp: line_num = 1 for line in fp: stripped_line = line.strip() if stripped_line and stripped_line[0] in vowels: print("Line {}: {}".format(line_num, stripped_line)) line_count += 1 line_num += 1 print("Total lines starting with a vowel:", line_count) except FileNotFoundError: print("Error: 'article.txt' not found.") count_vowel_start_lines() MySQL Interface 16. Insert Record into MySQL Table import mysql.connector def insert_data(): try: db = mysql.connector.connect(host="localhost", user="root", password="admin", database="YOUR_DATABASE_NAME") c = db.cursor() r = int(input("Enter roll no ")) n = input("Enter name ") p = int(input("Enter per ")) sql = "INSERT INTO student (roll, name, per) VALUES (%s, %s, %s)" c.execute(sql, (r, n, p)) db.commit() print("Record saved") except mysql.connector.Error as err: print(f"Error: {err}") if 'db' in locals() and db.is_connected(): db.rollback() finally: if 'db' in locals() and db.is_connected(): db.close() # insert_data() # Uncomment to run Note: Replace YOUR_DATABASE_NAME with your actual database name. 17. Display All Records from MySQL Table import mysql.connector def display_all(): try: db = mysql.connector.connect(host='localhost', user='root', passwd='admin', database='YOUR_DATABASE_NAME') c = db.cursor() sql = 'SELECT * FROM student;' c.execute(sql) data = c.fetchall() print("Number of rows :", c.rowcount) print("=========================") print("Roll No Name Per ") print("=========================") for eachrow in data: r, n, p = eachrow # Unpack tuple print(f"{r} {n} {p}") print("=========================") except mysql.connector.Error as err: print(f"Error: {err}") finally: if 'db' in locals() and db.is_connected(): db.close() # display_all() # Uncomment to run Note: Replace YOUR_DATABASE_NAME with your actual database name. 18. Search Record in MySQL Table import mysql.connector def search_roll(): try: db = mysql.connector.connect(host="localhost", user="root", passwd="admin", database="YOUR_DATABASE_NAME") c = db.cursor() roll_to_search = int(input("Enter roll no to search ")) sql = 'SELECT * FROM student WHERE roll = %s;' c.execute(sql, (roll_to_search,)) record = c.fetchone() if record: r, n, p = record print(f"{r} {n} {p}") else: print("Record is not present") except mysql.connector.Error as err: print(f"Error: {err}") finally: if 'db' in locals() and db.is_connected(): db.close() # search_roll() # Uncomment to run Note: Replace YOUR_DATABASE_NAME with your actual database name.