What is a variable in programming?
A named box that stores a value you can read and change.
age = 21
name = "Amit"
print(age, name) Curriculum
100 practice question(s) with answers.
A named box that stores a value you can read and change.
age = 21
name = "Amit"
print(age, name) Use the print function.
print("Hello, World!") Use printf.
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
} Use System.out.println.
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
} It defines what kind of value a variable holds.
age = 21 # int
score = 9.5 # float
name = "Amit" # string
print(type(age), type(score), type(name)) Runs code only when a condition is true.
n = 10
if n % 2 == 0:
print("Even")
else:
print("Odd") Check the remainder with the modulo operator.
def is_even(n):
return n % 2 == 0
print(is_even(10)) # True Repeats a block a fixed number of times.
for i in range(5):
print(i) # prints 0 1 2 3 4 Repeats while a condition is true.
i = 1
while i <= 5:
print(i)
i += 1 Use a loop or a formula.
total = sum(range(1, 11))
print(total) # 55 Use max or a comparison.
def max_of(a, b):
return a if a > b else b
print(max_of(4, 9)) # 9 A reusable named block of code.
def greet(name):
return "Hello, " + name
print(greet("Riya")) A function that calls itself with a base case.
def fact(n):
if n <= 1: # base case
return 1
return n * fact(n - 1)
print(fact(5)) # 120 An ordered collection of values.
nums = [3, 1, 2]
nums.append(4)
print(sorted(nums)) # [1, 2, 3, 4] Use a for loop.
for x in [10, 20, 30]:
print(x) Use the sum function.
print(sum([1, 2, 3, 4, 5])) # 15 Use len.
print(len([1, 2, 3])) # 3
print(len("hello")) # 5 Use slicing.
s = "hello"
print(s[::-1]) # olleh Compare the string with its reverse.
def is_pal(s):
return s == s[::-1]
print(is_pal("madam")) # True Loop and count.
def count_vowels(s):
return sum(1 for c in s.lower() if c in "aeiou")
print(count_vowels("hello")) # 2 A key-value store.
d = {"name": "Amit", "age": 21}
print(d["name"])
d["city"] = "Hyderabad" Use the in operator.
d = {"a": 1}
print("a" in d) # True An unordered collection of unique values.
s = {1, 2, 2, 3}
print(s) # {1, 2, 3} Convert to a set.
nums = [1, 2, 2, 3, 3]
print(list(set(nums))) # [1, 2, 3] Use a tuple unpack.
a, b = 5, 10
a, b = b, a
print(a, b) # 10 5 Repeatedly swap adjacent out-of-order items.
def bubble_sort(arr):
for i in range(len(arr)):
for j in range(len(arr) - 1 - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
print(bubble_sort([4, 2, 5, 1])) # [1, 2, 4, 5] Repeatedly pick the smallest and move it to the front.
def selection_sort(arr):
for i in range(len(arr)):
m = min(range(i, len(arr)), key=arr.__getitem__)
arr[i], arr[m] = arr[m], arr[i]
return arr
print(selection_sort([4, 2, 5, 1])) Search a sorted list by halving the range each step.
def binary_search(arr, key):
lo, hi = 0, len(arr) - 1
while lo <= hi:
mid = (lo + hi) // 2
if arr[mid] == key: return mid
if arr[mid] < key: lo = mid + 1
else: hi = mid - 1
return -1
print(binary_search([1, 3, 5, 7, 9], 7)) # 3 Check each element until you find the target.
def linear_search(arr, key):
for i, v in enumerate(arr):
if v == key: return i
return -1
print(linear_search([4, 2, 5, 1], 5)) # 2 Each term is the sum of the previous two.
def fib(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print([fib(i) for i in range(8)]) # [0,1,1,2,3,5,8,13] Test divisibility up to its square root.
import math
def is_prime(n):
if n < 2: return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0: return False
return True
print(is_prime(29)) # True Loop or recursion.
def factorial(n):
r = 1
for i in range(2, n + 1):
r *= i
return r
print(factorial(5)) # 120 Use the Euclidean algorithm.
def gcd(a, b):
while b:
a, b = b, a % b
return a
print(gcd(12, 18)) # 6 Product divided by GCD.
def lcm(a, b):
return (a * b) // gcd(a, b)
def gcd(a, b):
while b: a, b = b, a % b
return a
print(lcm(4, 6)) # 12 Use slicing or a loop.
arr = [1, 2, 3, 4]
arr.reverse()
print(arr) # [4, 3, 2, 1] Sort and index, or scan once.
nums = [5, 1, 9, 3, 9]
print(sorted(set(nums))[-2]) # 5 LIFO structure, last in first out.
stack = []
stack.append(1)
stack.append(2)
print(stack.pop()) # 2 FIFO structure, first in first out.
from collections import deque
q = deque([1, 2])
q.append(3)
print(q.popleft()) # 1 Use list.
print(list("hello")) # ['h','e','l','l','o'] Use join.
print("-".join(["a", "b", "c"])) # a-b-c Use split.
print("hello world".split()) # ['hello', 'world'] Catching and handling runtime errors gracefully.
try:
x = 10 // 0
except ZeroDivisionError:
print("Cannot divide by zero") Code to attempt an operation and handle errors.
try:
n = int("abc")
except ValueError:
n = 0
print(n) # 0 A blueprint for creating objects.
class Student:
def __init__(self, name):
self.name = name
def hello(self):
return "Hi " + self.name
s = Student("Riya")
print(s.hello()) An instance of a class with its own data.
A class deriving properties from another class.
class Animal:
def speak(self): return "..."
class Dog(Animal):
def speak(self): return "Woof"
print(Dog().speak()) A special method that runs when an object is created, like __init__.
A function that belongs to a class or object.
A variable that belongs to a class or object.
Organising code around objects with encapsulation, inheritance, polymorphism and abstraction.
Hiding internal data and exposing safe methods to use it.
The ability of different objects to respond to the same method in their own way.
Showing only essential details and hiding complexity.
A file of reusable code you can import.
import math
print(math.sqrt(16)) # 4.0 Import brings the module; from import brings a name directly.
from math import sqrt
print(sqrt(9)) Arguments passed by name.
def greet(name, greeting="Hi"):
return greeting + " " + name
print(greet("Amit", greeting="Hello")) A parameter with a default value used when none is passed.
A small anonymous one-line function.
add = lambda a, b: a + b
print(add(3, 4)) # 7 A function that yields values one at a time.
def countdown(n):
while n > 0:
yield n
n -= 1
print(list(countdown(3))) # [3, 2, 1] A compact way to build lists.
squares = [x * x for x in range(5)]
print(squares) # [0, 1, 4, 9, 16] A built-in operation on strings.
s = "Hello"
print(s.upper(), s.lower(), s.strip()) Use count.
print("banana".count("a")) # 3 = assigns a value; == compares values.
A shorthand if-else.
n = 7
print("Even" if n % 2 == 0 else "Odd") The else runs if the loop finishes without a break.
A no-op used where syntax requires a statement.
Converting one data type to another.
print(int("42") + 1) # 43
print(str(42) + "!") # 42! Use input.
name = input("Enter your name: ")
print("Hello", name) Reading the contents of a file.
with open("data.txt") as f:
print(f.read()) Open in write mode.
with open("out.txt", "w") as f:
f.write("Hello") It opens and automatically closes files safely.
An error that happens while the program runs.
An error because code does not follow language rules.
The code runs but gives the wrong result.
To step through code and inspect values to find bugs.
How runtime grows with input size, written as Big O.
Constant time, independent of input size.
Linear time, proportional to input size.
Log-linear time, typical of good sorting like merge sort.
Quadratic time, typical of nested loops like bubble sort.
O(log n).
O(n).
O(1).
O(n squared).
How memory usage grows with input size.
A notation for describing growth rates of algorithms.
An element chosen to partition the array into smaller and larger parts.
A divide-and-conquer sort that merges sorted halves.
def merge_sort(a):
if len(a) <= 1: return a
mid = len(a) // 2
l = merge_sort(a[:mid]); r = merge_sort(a[mid:])
res = []
while l and r:
res.append(l.pop(0) if l[0] < r[0] else r.pop(0))
return res + l + r
print(merge_sort([4, 2, 5, 1, 3])) A stable sort keeps the order of equal elements; an unstable one may not.
Makes the best local choice at each step hoping for the best global result.
Solving problems by combining solutions to overlapping subproblems and storing them.
Storing results of expensive calls to reuse them.
from functools import lru_cache
@lru_cache
def fib(n):
return n if n < 2 else fib(n-1) + fib(n-2)
print(fib(40)) Find two numbers that add to a target.
def two_sum(nums, target):
seen = {}
for i, v in enumerate(nums):
if target - v in seen:
return [seen[target - v], i]
seen[v] = i
return []
print(two_sum([2, 7, 11, 15], 9)) # [0, 1] Comparing strings by their characters and order.
Sort both and compare.
def is_anagram(a, b):
return sorted(a) == sorted(b)
print(is_anagram("listen", "silent")) # True Choose items with weights and values to maximise value within capacity.
An element that holds data and a pointer to the next node.
Follow the next pointers from the head until null.
A list where the last node points back to the head.
Visiting all nodes in a graph, using BFS or DFS.
Join the next training batch for guided practice, mock tests and personal feedback.