Click any cheatsheet to view full content. Download as PDF for offline access.
# Variables (no declaration needed)
name = "Murick" # String
age = 25 # Integer
price = 99.99 # Float
is_active = True # Boolean
items = [1, 2, 3] # List
person = {"name": "Ali"} # Dictionary
coords = (10, 20) # Tuple
unique = {1, 2, 3} # Set
# String methods
text = "Hello World"
text.lower() # "hello world"
text.upper() # "HELLO WORLD"
text.split(" ") # ["Hello", "World"]
text.replace("o","0") # "Hell0 W0rld"
text.strip() # Remove whitespace
f"Name: {name}" # f-string formatting
len(text) # 11
# List operations
nums = [1, 2, 3, 4, 5]
nums.append(6) # Add to end
nums.insert(0, 0) # Insert at index
nums.pop() # Remove last
nums.remove(3) # Remove by value
nums[1:3] # Slice [2, 3]
nums[-1] # Last element
# List comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in nums if x % 2 == 0]
# If-elif-else
if age >= 18:
print("Adult")
elif age >= 13:
print("Teen")
else:
print("Child")
# For loop
for item in items:
print(item)
for i in range(5): # 0 to 4
print(i)
# While loop
while count < 10:
count += 1
# Basic function
def greet(name):
return f"Hello, {name}!"
# Default parameters
def greet(name="World"):
return f"Hello, {name}!"
# *args and **kwargs
def func(*args, **kwargs):
print(args) # Tuple of positional args
print(kwargs) # Dict of keyword args
# Lambda functions
square = lambda x: x ** 2
add = lambda a, b: a + b
person = {"name": "Ali", "age": 25}
person["name"] # Get value
person.get("email", "") # Get with default
person["city"] = "Karachi" # Add/update
del person["age"] # Delete key
person.keys() # All keys
person.values() # All values
person.items() # Key-value pairs
# Dictionary comprehension
squares = {x: x**2 for x in range(5)}
# Read file
with open("file.txt", "r") as f:
content = f.read()
lines = f.readlines()
# Write file
with open("file.txt", "w") as f:
f.write("Hello World")
# Append to file
with open("file.txt", "a") as f:
f.write("New line")
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as e:
print(f"Error: {e}")
finally:
print("Always runs")
# Raise exception
raise ValueError("Invalid input")
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hi, I'm {self.name}"
# Inheritance
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
# Create instance
p = Person("Ali", 25)
print(p.greet())
import json # JSON handling
import datetime # Date/time
import os # OS operations
import re # Regular expressions
import random # Random numbers
import math # Math functions
# Popular packages
import requests # HTTP requests
import pandas as pd # Data analysis
import numpy as np # Numerical computing
// let - block scoped, reassignable
let name = "Murick";
name = "Tech"; // OK
// const - block scoped, not reassignable
const PI = 3.14159;
// PI = 3; // Error!
// const with objects (properties can change)
const user = { name: "Ali" };
user.name = "Hassan"; // OK
// user = {}; // Error!
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
// With single parameter
const square = x => x * x;
// With function body
const greet = name => {
const msg = `Hello, ${name}!`;
return msg;
};
// In callbacks
const nums = [1, 2, 3];
const doubled = nums.map(n => n * 2);
const name = "Ali";
const age = 25;
// String interpolation
const msg = `Hello, ${name}! You are ${age}.`;
// Multi-line strings
const html = `
<div class="card">
<h2>${name}</h2>
<p>Age: ${age}</p>
</div>
`;
// Expressions in templates
const price = `Total: $${(100 * 1.18).toFixed(2)}`;
// Array destructuring
const [a, b, c] = [1, 2, 3];
const [first, ...rest] = [1, 2, 3, 4];
// Object destructuring
const { name, age } = { name: "Ali", age: 25 };
// With aliases
const { name: userName } = user;
// Default values
const { city = "Unknown" } = user;
// Nested destructuring
const { address: { city } } = user;
// In function parameters
const greet = ({ name, age }) => {
console.log(`${name} is ${age}`);
};
// Spread - expand arrays/objects
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1,2,3,4,5]
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
// Clone array/object
const clone = [...arr1];
const objClone = { ...obj1 };
// Rest - collect remaining
const [first, ...others] = [1, 2, 3, 4];
// first = 1, others = [2, 3, 4]
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
// Creating a Promise
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Data"), 1000);
});
};
// Using .then()
fetchData()
.then(data => console.log(data))
.catch(err => console.error(err));
// Async/Await
async function getData() {
try {
const data = await fetchData();
console.log(data);
} catch (err) {
console.error(err);
}
}
// Promise.all - parallel execution
const results = await Promise.all([
fetch(url1),
fetch(url2)
]);
const nums = [1, 2, 3, 4, 5];
// map - transform each element
const doubled = nums.map(n => n * 2);
// filter - keep matching elements
const evens = nums.filter(n => n % 2 === 0);
// reduce - accumulate to single value
const sum = nums.reduce((acc, n) => acc + n, 0);
// find - first matching element
const found = nums.find(n => n > 3);
// some/every - test conditions
const hasEven = nums.some(n => n % 2 === 0);
const allPositive = nums.every(n => n > 0);
// includes - check existence
const hasThree = nums.includes(3);
const user = {
name: "Ali",
address: { city: "Karachi" }
};
// Optional chaining (?.)
const city = user?.address?.city; // "Karachi"
const zip = user?.address?.zip; // undefined
// With arrays
const first = arr?.[0];
// With functions
const result = obj?.method?.();
// Nullish coalescing (??)
const name = user.name ?? "Guest";
// Returns right side only if left is null/undefined
// Difference from ||
const count = 0 || 10; // 10 (0 is falsy)
const count = 0 ?? 10; // 0 (0 is not null)
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hi, I'm ${this.name}`;
}
static create(name) {
return new Person(name, 0);
}
}
// Inheritance
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
}
const student = new Student("Ali", 20, "A");
// Named exports (utils.js)
export const add = (a, b) => a + b;
export const PI = 3.14159;
// Default export
export default class Calculator { }
// Named imports
import { add, PI } from './utils.js';
// Default import
import Calculator from './calculator.js';
// Import all
import * as utils from './utils.js';
// Rename imports
import { add as sum } from './utils.js';
import { useState } from 'react';
function Counter() {
// Basic usage
const [count, setCount] = useState(0);
// With objects
const [user, setUser] = useState({ name: '', age: 0 });
// Update state
setCount(count + 1);
setCount(prev => prev + 1); // Functional update
// Update object (spread to preserve other fields)
setUser({ ...user, name: 'Ali' });
setUser(prev => ({ ...prev, name: 'Ali' }));
return (
<button onClick={() => setCount(c => c + 1)}>
Count: {count}
</button>
);
}
import { useEffect } from 'react';
function Component() {
// Run on every render
useEffect(() => {
console.log('Rendered');
});
// Run once on mount
useEffect(() => {
fetchData();
}, []);
// Run when dependency changes
useEffect(() => {
fetchUser(userId);
}, [userId]);
// Cleanup function
useEffect(() => {
const subscription = subscribe();
return () => subscription.unsubscribe();
}, []);
// Async in useEffect
useEffect(() => {
const loadData = async () => {
const data = await fetchData();
setData(data);
};
loadData();
}, []);
}
import { createContext, useContext } from 'react';
// Create context
const ThemeContext = createContext('light');
// Provider component
function App() {
return (
<ThemeContext.Provider value="dark">
<ChildComponent />
</ThemeContext.Provider>
);
}
// Consume context
function ChildComponent() {
const theme = useContext(ThemeContext);
return <div className={theme}>...</div>;
}
// With custom hook
const useTheme = () => useContext(ThemeContext);
import { useReducer } from 'react';
// Reducer function
const reducer = (state, action) => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
case 'SET':
return { count: action.payload };
default:
return state;
}
};
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
<p>{state.count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
<button onClick={() => dispatch({ type: 'SET', payload: 10 })}>Set 10</button>
</>
);
}
import { useMemo } from 'react';
function ExpensiveComponent({ items, filter }) {
// Only recalculate when items or filter changes
const filteredItems = useMemo(() => {
return items.filter(item =>
item.name.includes(filter)
);
}, [items, filter]);
// Expensive calculation
const total = useMemo(() => {
return items.reduce((sum, item) => sum + item.price, 0);
}, [items]);
return <List items={filteredItems} />;
}
// Use when:
// - Expensive calculations
// - Referential equality matters
// - Preventing unnecessary child re-renders
import { useCallback } from 'react';
function Parent() {
const [count, setCount] = useState(0);
// Without useCallback - new function every render
const handleClick = () => setCount(c => c + 1);
// With useCallback - same function reference
const handleClick = useCallback(() => {
setCount(c => c + 1);
}, []);
// With dependencies
const handleSubmit = useCallback((data) => {
submitForm(userId, data);
}, [userId]);
return <Child onClick={handleClick} />;
}
// Use when passing callbacks to optimized child components
// that rely on reference equality (React.memo)
import { useRef, useEffect } from 'react';
function Component() {
// DOM reference
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus(); // Focus input on mount
}, []);
// Mutable value (doesn't trigger re-render)
const renderCount = useRef(0);
renderCount.current++;
// Store previous value
const prevValue = useRef();
useEffect(() => {
prevValue.current = value;
}, [value]);
return (
<input ref={inputRef} />
);
}
// useLocalStorage hook
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
// useFetch hook
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(setData)
.catch(setError)
.finally(() => setLoading(false));
}, [url]);
return { data, loading, error };
}
# Set user info
git config --global user.name "Your Name"
git config --global user.email "email@example.com"
# View config
git config --list
# Initialize repository
git init
# Clone repository
git clone https://github.com/user/repo.git
git clone git@github.com:user/repo.git
# Check status
git status
# Add files to staging
git add filename.txt # Single file
git add . # All files
git add *.js # Pattern match
# Commit changes
git commit -m "Commit message"
git commit -am "Add and commit" # Tracked files only
# View commit history
git log
git log --oneline
git log --graph --oneline
# Show changes
git diff # Unstaged changes
git diff --staged # Staged changes
git diff HEAD~1 # Compare with previous commit
# List branches
git branch # Local branches
git branch -r # Remote branches
git branch -a # All branches
# Create branch
git branch feature-name
git checkout -b feature-name # Create and switch
# Switch branch
git checkout branch-name
git switch branch-name # Git 2.23+
# Delete branch
git branch -d branch-name # Safe delete
git branch -D branch-name # Force delete
git push origin --delete branch-name # Remote
# Rename branch
git branch -m old-name new-name
# Merge branch into current
git merge feature-branch
# Merge with no fast-forward
git merge --no-ff feature-branch
# Abort merge
git merge --abort
# Rebase current branch onto main
git rebase main
# Interactive rebase (edit last 3 commits)
git rebase -i HEAD~3
# Abort rebase
git rebase --abort
# Continue after resolving conflicts
git rebase --continue
# View remotes
git remote -v
# Add remote
git remote add origin URL
# Fetch changes
git fetch origin
# Pull changes
git pull origin main
git pull --rebase origin main
# Push changes
git push origin main
git push -u origin main # Set upstream
git push --force # Force push (careful!)
# Push new branch
git push -u origin feature-branch
# Discard working directory changes
git checkout -- filename
git restore filename # Git 2.23+
# Unstage files
git reset HEAD filename
git restore --staged filename
# Undo last commit (keep changes)
git reset --soft HEAD~1
# Undo last commit (discard changes)
git reset --hard HEAD~1
# Revert commit (creates new commit)
git revert commit-hash
# Amend last commit
git commit --amend -m "New message"
# Stash changes
git stash
git stash save "message"
# List stashes
git stash list
# Apply stash
git stash apply # Keep in stash
git stash pop # Remove from stash
# Apply specific stash
git stash apply stash@{2}
# Drop stash
git stash drop stash@{0}
# Clear all stashes
git stash clear
-- Basic SELECT
SELECT * FROM users;
SELECT name, email FROM users;
-- With conditions
SELECT * FROM users WHERE age > 18;
SELECT * FROM users WHERE city = 'Karachi' AND age >= 25;
SELECT * FROM users WHERE city IN ('Karachi', 'Lahore');
SELECT * FROM users WHERE name LIKE 'A%'; -- Starts with A
SELECT * FROM users WHERE email IS NOT NULL;
-- Sorting
SELECT * FROM users ORDER BY name ASC;
SELECT * FROM users ORDER BY created_at DESC;
-- Limiting results
SELECT * FROM users LIMIT 10;
SELECT * FROM users LIMIT 10 OFFSET 20; -- Pagination
-- INNER JOIN (matching rows only)
SELECT users.name, orders.total
FROM users
INNER JOIN orders ON users.id = orders.user_id;
-- LEFT JOIN (all from left + matching from right)
SELECT users.name, orders.total
FROM users
LEFT JOIN orders ON users.id = orders.user_id;
-- RIGHT JOIN (all from right + matching from left)
SELECT users.name, orders.total
FROM users
RIGHT JOIN orders ON users.id = orders.user_id;
-- FULL OUTER JOIN (all from both)
SELECT users.name, orders.total
FROM users
FULL OUTER JOIN orders ON users.id = orders.user_id;
-- Multiple JOINs
SELECT u.name, o.total, p.name as product
FROM users u
JOIN orders o ON u.id = o.user_id
JOIN products p ON o.product_id = p.id;
-- COUNT
SELECT COUNT(*) FROM users;
SELECT COUNT(DISTINCT city) FROM users;
-- SUM, AVG, MIN, MAX
SELECT SUM(total) FROM orders;
SELECT AVG(price) FROM products;
SELECT MIN(age), MAX(age) FROM users;
-- GROUP BY
SELECT city, COUNT(*) as user_count
FROM users
GROUP BY city;
-- HAVING (filter groups)
SELECT city, COUNT(*) as count
FROM users
GROUP BY city
HAVING COUNT(*) > 10;
-- Combined example
SELECT category, AVG(price) as avg_price
FROM products
GROUP BY category
HAVING AVG(price) > 100
ORDER BY avg_price DESC;
-- Subquery in WHERE
SELECT * FROM users
WHERE id IN (SELECT user_id FROM orders WHERE total > 1000);
-- Subquery in FROM
SELECT avg_total FROM (
SELECT user_id, AVG(total) as avg_total
FROM orders
GROUP BY user_id
) as user_averages;
-- Correlated subquery
SELECT * FROM users u
WHERE EXISTS (
SELECT 1 FROM orders o WHERE o.user_id = u.id
);
-- Subquery with comparison
SELECT * FROM products
WHERE price > (SELECT AVG(price) FROM products);
-- INSERT
INSERT INTO users (name, email, age)
VALUES ('Ali', 'ali@email.com', 25);
-- Insert multiple rows
INSERT INTO users (name, email) VALUES
('Ali', 'ali@email.com'),
('Sara', 'sara@email.com');
-- UPDATE
UPDATE users SET age = 26 WHERE id = 1;
UPDATE users SET status = 'active' WHERE created_at < '2024-01-01';
-- DELETE
DELETE FROM users WHERE id = 1;
DELETE FROM users WHERE status = 'inactive';
-- TRUNCATE (delete all rows)
TRUNCATE TABLE logs;
-- Create table
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE,
age INT DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Add column
ALTER TABLE users ADD COLUMN phone VARCHAR(20);
-- Modify column
ALTER TABLE users MODIFY COLUMN name VARCHAR(200);
-- Drop column
ALTER TABLE users DROP COLUMN phone;
-- Create index
CREATE INDEX idx_email ON users(email);
-- Drop table
DROP TABLE users;
.container {
display: flex;
/* Direction */
flex-direction: row; /* default */
flex-direction: row-reverse;
flex-direction: column;
flex-direction: column-reverse;
/* Wrapping */
flex-wrap: nowrap; /* default */
flex-wrap: wrap;
flex-wrap: wrap-reverse;
/* Main axis alignment */
justify-content: flex-start; /* default */
justify-content: flex-end;
justify-content: center;
justify-content: space-between;
justify-content: space-around;
justify-content: space-evenly;
/* Cross axis alignment */
align-items: stretch; /* default */
align-items: flex-start;
align-items: flex-end;
align-items: center;
align-items: baseline;
/* Multi-line alignment */
align-content: flex-start;
align-content: center;
align-content: space-between;
/* Gap between items */
gap: 20px;
row-gap: 10px;
column-gap: 20px;
}
.item {
/* Order (default: 0) */
order: 1;
/* Grow factor (default: 0) */
flex-grow: 1; /* Take available space */
/* Shrink factor (default: 1) */
flex-shrink: 0; /* Don't shrink */
/* Base size */
flex-basis: 200px;
flex-basis: 25%;
/* Shorthand: grow shrink basis */
flex: 1; /* flex: 1 1 0% */
flex: 0 0 200px; /* Fixed width, no grow/shrink */
flex: 1 1 auto; /* Grow and shrink from content */
/* Self alignment (override container) */
align-self: auto;
align-self: flex-start;
align-self: flex-end;
align-self: center;
align-self: stretch;
}
/* Center everything */
.center-all {
display: flex;
justify-content: center;
align-items: center;
}
/* Space between with wrap */
.card-grid {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
/* Sticky footer layout */
.page {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.main { flex: 1; }
/* Navigation bar */
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
}
/* Equal width columns */
.columns {
display: flex;
}
.column { flex: 1; }
.grid {
display: grid;
/* Define columns */
grid-template-columns: 200px 200px 200px;
grid-template-columns: 1fr 1fr 1fr;
grid-template-columns: repeat(3, 1fr);
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
/* Define rows */
grid-template-rows: 100px auto 100px;
grid-auto-rows: minmax(100px, auto);
/* Gap */
gap: 20px;
row-gap: 10px;
column-gap: 20px;
/* Alignment */
justify-items: start | end | center | stretch;
align-items: start | end | center | stretch;
/* Content alignment */
justify-content: start | end | center | space-between;
align-content: start | end | center | space-between;
}
.item {
/* Column placement */
grid-column-start: 1;
grid-column-end: 3;
grid-column: 1 / 3; /* Shorthand */
grid-column: 1 / span 2; /* Span 2 columns */
/* Row placement */
grid-row-start: 1;
grid-row-end: 3;
grid-row: 1 / 3;
/* Area shorthand: row-start / col-start / row-end / col-end */
grid-area: 1 / 1 / 3 / 3;
/* Self alignment */
justify-self: start | end | center | stretch;
align-self: start | end | center | stretch;
}
/* Named grid areas */
.grid {
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
/* Auto-fit responsive grid */
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
}
/* Holy grail layout */
.layout {
display: grid;
grid-template-columns: 200px 1fr 200px;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
}
/* Card grid with fixed columns */
.cards {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 24px;
}
@media (max-width: 768px) {
.cards {
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 480px) {
.cards {
grid-template-columns: 1fr;
}
}
Comprehensive guides on specific topics. Enter email to download.
Learn to design clean, scalable APIs with proper naming, versioning, error handling, and authentication.
50 common interview questions with answers for Pakistani tech companies like Systems Limited, 10Pearls, Netsol.
From installation to deployment. Containers, images, volumes, networks, and docker-compose explained.
Naming conventions, function design, SOLID principles, and refactoring techniques with examples.
Solutions from our top-performing interns. Enter email to view code.
Build a shopping cart with add/remove items, quantity updates, discount codes, and checkout flow.
Create a chat app with rooms, typing indicators, message history, and online status.
Design a RESTful API with authentication, CRUD operations, filtering, and pagination.
Build a weather app with location search, 5-day forecast, and data visualization.
Subscribe to receive new cheatsheets, guides, and coding challenges directly in your inbox.