0% found this document useful (0 votes)
14 views7 pages

PW Python Syntax Cheat Sheet

This cheat sheet provides essential Python syntax rules and concepts for CBSE Class 12 Computer Science Board Exam 2026. It covers topics like functions, exception handling, recursion, scope, modules, data structures (stack and queue), and sorting/searching algorithms, all organized for quick reference. The document is designed for last-minute revision with color-coded sections and examples.

Uploaded by

bissaprateek
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)
14 views7 pages

PW Python Syntax Cheat Sheet

This cheat sheet provides essential Python syntax rules and concepts for CBSE Class 12 Computer Science Board Exam 2026. It covers topics like functions, exception handling, recursion, scope, modules, data structures (stack and queue), and sorting/searching algorithms, all organized for quick reference. The document is designed for last-minute revision with color-coded sections and examples.

Uploaded by

bissaprateek
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

CBSE CLASS 12 | COMPUTER SCIENCE (083) | BOARD EXAM 2026

QUICK REFERENCE CHEAT SHEET

🐍🐍
PYTHON SYNTAX CHEAT SHEET
All Important Syntax Rules for CBSE CS Board Exam 2026

How to use this cheat sheet


This is your last-minute revision companion.
All entries are sorted by topic and color-coded for quick scanning.
⭐ = Most important / Most frequently tested in board exams
Print and stick on your study wall — revise 10 minutes every day!
1. Functions — All Syntax Forms

Function Syntax — Complete Reference

# ── Basic Function ─────────────────────────────────────────


def function_name(param1, param2):
"""Docstring — optional but good practice"""
# function body (indented by 4 spaces)
return value # optional — returns None if absent

# Call:
result = function_name(arg1, arg2)

# ── Default Arguments (defaults MUST come AFTER non-defaults) ─


def greet(name, msg='Hello'):
print(msg, name)

greet('Aarav') # Uses default: Hello Aarav


greet('Priya', 'Hi') # Overrides: Hi Priya

# ── Keyword Arguments ───────────────────────────────────────


def show(name, age, city):
print(name, age, city)

show(age=17, city='Delhi', name='Rohan') # Order doesn't matter

# ── *args — Variable Positional (creates TUPLE) ─────────────


def add_all(*numbers):
return sum(numbers) # numbers is a TUPLE

add_all(1, 2, 3, 4, 5) # numbers=(1,2,3,4,5)

# ── **kwargs — Variable Keyword (creates DICT) ──────────────


def display(**info):
for key, val in [Link]():
print(key, ':', val)

display(name='Aarav', age=17, city='Delhi')

# ── Combined — Correct ORDER ────────────────────────────────


def func(pos, default=0, *args, **kwargs): # ← correct order
pass

# ── Lambda Function ─────────────────────────────────────────


square = lambda x: x * x
is_even = lambda n: n % 2 == 0
add = lambda a, b: a + b
grade = lambda m: 'A' if m>=90 else 'B' if m>=75 else 'C'

# ── Return Multiple Values (returns TUPLE) ──────────────────


def swap(a, b):
return b, a # returns tuple (b, a)

x, y = swap(3, 5) # x=5, y=3 (unpacking)


2. Exception Handling — All Forms

Exception Handling Syntax

# ── Complete Structure ──────────────────────────────────────


try:
risky_code() # Code that might raise exception
except ExceptionType1:
handle_error1() # Runs ONLY if ExceptionType1 raised
except (ExceptionType2, ExceptionType3):
handle_error23() # Handles multiple exception types
except Exception as e:
print('Error:', e) # Catches ANY exception; 'e' = message
else:
success_code() # Runs ONLY if NO exception occurred
finally:
cleanup() # ALWAYS runs — exception or not

# ── raise Statement ─────────────────────────────────────────


raise ValueError('Age cannot be negative!') # Raise new
raise # Re-raise current

# ── User-Defined Exception ──────────────────────────────────


class MyError(Exception): # MUST inherit Exception
pass

class DetailedError(Exception):
def __init__(self, msg):
super().__init__(msg) # Pass to parent

# ── Common Exception Types ──────────────────────────────────


# ZeroDivisionError — 10/0
# ValueError — int('abc')
# TypeError — '5' + 5
# IndexError — [1,2,3][10]
# KeyError — {'a':1}['b']
# FileNotFoundError — open('[Link]','r')
# NameError — print(undefined_var)
# AttributeError — ''.nonexistent_method()
# ImportError — import nonexistent_module
# EOFError — [Link]() at end of file
# RecursionError — recursion without base case

3. Recursion Syntax

Recursion — Common Patterns

# ── Recursive Function Template ─────────────────────────────


def recursive_func(n):
if base_condition: # ← BASE CASE (MUST have this!)
return base_value
return operation + recursive_func(smaller_n) # Recursive case

# ── Factorial ────────────────────────────────────────────────
def factorial(n):
if n == 0 or n == 1: # Base case
return 1
return n * factorial(n-1) # Recursive case

# ── Fibonacci ────────────────────────────────────────────────
def fibonacci(n):
if n <= 1: # Base case
return n
return fibonacci(n-1) + fibonacci(n-2)

# ── Sum of Digits ────────────────────────────────────────────


def sum_digits(n):
n = abs(n)
if n < 10: # Base case: single digit
return n
return (n % 10) + sum_digits(n // 10)

# ── Palindrome Check ─────────────────────────────────────────


def is_palindrome(s, start, end):
if start >= end: # Base case
return True
if s[start] != s[end]:
return False
return is_palindrome(s, start+1, end-1)

4. Scope — global & nonlocal

Scope — global & nonlocal Keywords

x = 10 # Global variable

def demo():
x = 20 # Local variable (shadows global)
print(x) # Prints 20 (local)

demo()
print(x) # Prints 10 (global unchanged)

# ── global keyword ──────────────────────────────────────────


def modify_global():
global x # Declare: use the GLOBAL x
x = 99 # Now modifies global x

modify_global()
print(x) # Prints 99

# ── nonlocal keyword ────────────────────────────────────────


def outer():
count = 0
def inner():
nonlocal count # Refers to outer's 'count'
count += 1
inner()
print(count) # Prints 1 (outer's count modified)

# ── LEGB Rule (search order) ────────────────────────────────


# L (Local) → E (Enclosing) → G (Global) → B (Built-in)

5. Modules — Import Syntax

Module Syntax — math, random, statistics

# ── Four Ways to Import ─────────────────────────────────────


import math # Full import — use [Link]()
import math as m # Alias — use [Link]()
from math import sqrt # Selective — use sqrt() directly
from math import sqrt, pi, ceil # Multiple selective imports
from math import * # Import ALL (avoid — pollutes namespace)

# ── math module ─────────────────────────────────────────────


[Link](25) # → 5.0 (square root)
[Link](4.2) # → 5 (rounds UP)
[Link](-4.2) # → -4 (still rounds UP towards +infinity)
[Link](4.9) # → 4 (rounds DOWN)
[Link](-4.9) # → -5 (rounds DOWN towards -infinity)
[Link](2, 10) # → 1024.0 (returns FLOAT always)
[Link](-7.5) # → 7.5 (absolute value, float)
[Link] # → 3.141592653589793
math.e # → 2.718281828459045
[Link](100, 10) # → 2.0 (log base 10 of 100)

# ── random module ───────────────────────────────────────────


[Link]() # Float: 0.0 <= x < 1.0
[Link](1, 6) # Integer: 1 to 6 INCLUSIVE
[Link](0, 100, 5) # From 0,5,10,...,95 (excludes 100)
[Link]([10,20,30]) # Random element from sequence
[Link](range(1,51),3) # 3 UNIQUE elements (no repeat)
[Link](my_list) # Shuffles in-place (returns None!)

# ── statistics module ───────────────────────────────────────


[Link]([4,7,2,9]) # Arithmetic mean
[Link]([4,7,2,9]) # Middle value
[Link]([1,2,2,3]) # Most frequent value
[Link]([4,7,2,9]) # Standard deviation

6. Stack & Queue — Complete Syntax

Stack & Queue Syntax — List and Linked List


# ── STACK using list ────────────────────────────────────────
stack = []

def push(item): # PUSH


[Link](item)

def pop(): # POP


if not stack: print('Underflow!'); return None
return [Link]() # removes last = TOP

def peek(): # PEEK (view top)


return stack[-1] if stack else None

def isEmpty():
return len(stack) == 0

# ── QUEUE using list ─────────────────────────────────────────


queue = []

def enqueue(item): # ENQUEUE


[Link](item) # adds to REAR

def dequeue(): # DEQUEUE


if not queue: print('Underflow!'); return None
return [Link](0) # removes first = FRONT

# ── NODE & LINKED LIST ──────────────────────────────────────


class Node:
def __init__(self, data):
[Link] = data
[Link] = None # MUST initialise to None

# ── STACK using Linked List ──────────────────────────────────


class Stack:
def __init__(self):
[Link] = None # HEAD = TOP

def push(self, data):


node = Node(data)
[Link] = [Link] # new node → old top
[Link] = node # update top

def pop(self):
if not [Link]: return None
val = [Link]
[Link] = [Link] # advance top
return val

7. Sorting & Searching Algorithms

Sorting & Searching Algorithm Syntax


# ── BUBBLE SORT ─────────────────────────────────────────────
def bubble_sort(lst):
n = len(lst)
for i in range(n-1): # n-1 passes
swapped = False # optimisation flag
for j in range(n-1-i): # inner loop shrinks each pass
if lst[j] > lst[j+1]: # compare adjacent
lst[j], lst[j+1] = lst[j+1], lst[j] # swap
swapped = True
if not swapped: break # already sorted — stop early

# ── INSERTION SORT ──────────────────────────────────────────


def insertion_sort(lst):
for i in range(1, len(lst)): # start from second element
key = lst[i] # element to insert
j = i - 1
while j >= 0 and lst[j] > key: # shift larger elements right
lst[j+1] = lst[j]
j -= 1
lst[j+1] = key # place key at correct position

# ── SELECTION SORT ──────────────────────────────────────────


def selection_sort(lst):
n = len(lst)
for i in range(n-1):
min_idx = i # assume current is minimum
for j in range(i+1, n): # find actual minimum
if lst[j] < lst[min_idx]: min_idx = j
if min_idx != i: # only swap if needed
lst[i], lst[min_idx] = lst[min_idx], lst[i]

# ── LINEAR SEARCH ───────────────────────────────────────────


def linear_search(lst, target):
for i in range(len(lst)):
if lst[i] == target: return i
return -1

# ── BINARY SEARCH (list MUST be sorted!) ────────────────────


def binary_search(lst, target):
low, high = 0, len(lst)-1
while low <= high:
mid = (low + high) // 2 # ← MUST use // (integer div)
if lst[mid] == target: return mid
elif lst[mid] < target: low = mid + 1 # right half
else: high = mid - 1 # left half
return -1 # not found

Python Syntax Cheat Sheet | CBSE Class 12 CS | Board Exam 2026

You might also like