Loading...
Search for a command to run...
Loading...
Search and browse syntax references for all supported languages. Copy code snippets with one click.
Python variables are dynamically typed
name = "Alice"
age = 25
height = 1.75
is_student = TrueCommon Python data types
type(42) # <class 'int'>
type(3.14) # <class 'float'>
type("hello") # <class 'str'>
type(True) # <class 'bool'>
type([1,2,3]) # <class 'list'>Common string operations
"hello".upper() # HELLO
"HELLO".lower() # hello
" hi ".strip() # hi
"a,b,c".split(",") # ['a','b','c']
"-".join(["a","b"]) # a-bString interpolation
name = "Alice"
age = 25
print(f"{name} is {age} years old")
print(f"Pi = {3.14159:.2f}")Common list methods
nums = [1, 2, 3]
nums.append(4)
nums.insert(0, 0)
nums.pop()
nums.sort()
[x*2 for x in nums]Common dictionary methods
d = {"a": 1, "b": 2}
d["c"] = 3
d.get("x", 0)
d.keys()
d.values()
d.items()
{k: v*2 for k,v in d.items()}If-elif-else and ternary
if x > 0:
print("positive")
elif x == 0:
print("zero")
else:
print("negative")
# Ternary
res = "even" if x % 2 == 0 else "odd"Loop patterns
for i in range(5):
for i, x in enumerate(lst):
for k, v in d.items():
while x > 0:
[x**2 for x in range(10) if x % 2 == 0]Function definition patterns
def add(a, b=0, *args, **kwargs):
return a + b
# Lambda
square = lambda x: x**2
# Decorator
def timer(fn):
def wrapper(*a, **kw):
import time
start = time.time()
result = fn(*a, **kw)
print(f"took {time.time()-start}s")
return result
return wrapperClass definition structure
class Dog:
species = "Canine"
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says Woof!"Reading and writing files
with open("file.txt", "r") as f:
content = f.read()
lines = f.readlines()
for line in f:
print(line.strip())
with open("file.txt", "w") as f:
f.write("Hello\n")Variable declarations and type checking
let name = "Alice"
const age = 25
var old = "avoid"
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof {} // "object"
typeof [] // "object"String manipulation
"hello".toUpperCase()
"HELLO".toLowerCase()
" hi ".trim()
"a,b,c".split(",")
["a","b"].join("-")
`Hello, ${name}!`Essential array operations
nums.push(4)
nums.pop()
nums.unshift(0)
nums.shift()
nums.slice(1,3)
nums.splice(1,1)
nums.map(x => x*2)
nums.filter(x => x > 2)
nums.reduce((a,b) => a+b, 0)Arrow function syntax
const add = (a, b) => a + b
const square = x => x * x
const greet = name => `Hello ${name}`
// Higher-order
const twice = fn => x => fn(fn(x))Object manipulation
const user = { name: "Alice", age: 25 }
user.email = "a@b.com"
const { name, age } = user
const clone = { ...user }
Object.keys(user)
Object.values(user)
Object.entries(user)Async patterns
fetch(url)
.then(res => res.json())
.catch(err => console.error(err))
async function getData() {
try {
const res = await fetch(url)
return await res.json()
} catch (err) {
console.error(err)
}
}
const [a, b] = await Promise.all([p1, p2])DOM selection and manipulation
document.querySelector('.class')
document.querySelectorAll('div')
elem.textContent = 'text'
elem.classList.add('active')
elem.style.color = '#D946EF'
elem.addEventListener('click', e => {
console.log(e.target)
})Standard HTML5 template
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page</title>
</head>
<body>
<header>Nav</header>
<main>Content</main>
<footer>Footer</footer>
</body>
</html>Flexbox layout reference
.container {
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
gap: 1rem;
}
.item {
flex: 1 1 200px;
}CSS Grid layout patterns
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
}
.featured {
grid-column: span 2;
}
.responsive {
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
}Transitions and keyframe animations
.element {
transition: all 0.3s ease;
}
@keyframes slideIn {
from { opacity: 0; transform: translateX(-20px); }
to { opacity: 1; transform: translateX(0); }
}Basic Java program structure
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}Java Collections Framework
List<String> list = new ArrayList<>();
list.add("a");
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
list.stream()
.filter(s -> s.startsWith("a"))
.map(String::toUpperCase)
.collect(Collectors.toList());Basic C# program
using System;
class Program {
static void Main(string[] args) {
Console.WriteLine("Hello, World!");
}
}LINQ query and method syntax
var numbers = new[] { 1, 2, 3, 4, 5 };
var evens = from n in numbers
where n % 2 == 0
select n;
var squares = numbers
.Where(n => n % 2 == 0)
.Select(n => n * n);Basic C++ program
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}Pointer and reference syntax
int value = 42;
int* ptr = &value;
int& ref = value;
*ptr = 100;
auto unique = std::make_unique<int>(42);
auto shared = std::make_shared<int>(100);STL algorithms and containers
#include <vector>
#include <algorithm>
std::vector<int> nums = {3, 1, 4, 1, 5};
std::sort(nums.begin(), nums.end());
auto it = std::find(nums.begin(), nums.end(), 4);
std::count_if(nums.begin(), nums.end(),
[](int n) { return n % 2 == 0; });Try/except/else/finally flow
try:
result = 10 / int(x)
except ZeroDivisionError:
print("cannot divide by zero")
except ValueError as e:
print(f"bad input: {e}")
except Exception:
print("unexpected")
else:
print("no error")
finally:
print("always runs")Set operations and tuple unpacking
s = {1, 2, 3}
s.add(4)
s.union({5, 6})
s.intersection({2, 3})
s.difference({1})
t = (1, 2, 3)
a, b, c = t
unique = list(set([1, 1, 2, 3, 3])) # [1, 2, 3]Import forms and entry-point pattern
import math
from datetime import datetime
import numpy as np
math.sqrt(16) # 4.0
datetime.now() # current time
np.array([1, 2, 3]).sum() # 6
if __name__ == "__main__":
main()datetime formatting and arithmetic
from datetime import datetime, timedelta
now = datetime.now()
now.strftime("%Y-%m-%d %H:%M") # format
parsed = datetime.fromisoformat("2026-01-15")
parsed + timedelta(days=7) # add days
tz = now.astimezone()
ts = now.timestamp() # unix secondsCommon regular expression operations
import re
re.search(r"\d+", "abc 123").group() # "123"
re.findall(r"\b\w{3}\b", "one two three")
re.sub(r"\s+", "-", "a b") # "a-b"
re.match(r"^\d", "1abc") # match at start
email = r"[\w.+-]+@[\w-]+\.[\w.]+"Array and object destructuring
const [a, b, ...rest] = [1, 2, 3, 4]
const { name, age = 18, email: mail } = user
const clone = { ...user, age: 26 }
const merged = [...nums1, ...nums2]
// Function params
function draw({ x = 0, y = 0, color = "red" }) {}Closures, IIFE, and encapsulation
function counter() {
let count = 0
return () => ++count
}
const next = counter()
next() // 1
// Module pattern
const store = (() => {
let data = []
return {
add: (x) => data.push(x),
all: () => data,
}
})()Unique values and key-value stores
const set = new Set([1, 2, 2, 3])
set.has(2) // true
const map = new Map()
map.set("a", 1)
map.get("a") // 1
map.has("b") // false
const counts = new Map()
for (const w of words)
counts.set(w, (counts.get(w) || 0) + 1)try/catch/finally and custom errors
try {
const res = await fetch(url)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const data = await res.json()
} catch (err) {
console.error("fetch failed:", err)
} finally {
cleanup()
}
// Custom errors
class ValidationError extends Error {}
throw new ValidationError("bad input")Selector reference with combinators
/* Basic */
.class, .other { }
#id { }
[data-type="a"] { }
/* Combinators */
.parent > .child /* direct child */
.a + .b /* adjacent sibling */
.a ~ .b /* general sibling */
/* Pseudo */
li:nth-child(odd) { }
button:hover { }
input:focus { }
.link::after { }CSS variables with fallbacks
:root {
--accent: #6366F1;
--radius: 12px;
--space: 1rem;
}
.card {
border: 1px solid color-mix(in srgb, var(--accent) 40%, transparent);
border-radius: var(--radius);
padding: var(--space);
background: var(--card-bg, #1a1a1a); /* fallback */
}Fluid grids and breakpoints
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 1rem;
}
@media (max-width: 768px) {
.nav { flex-direction: column; }
.hero { font-size: 1.5rem; }
}
@media (prefers-reduced-motion: reduce) {
* { animation: none !important; transition: none !important; }
}Accessible form markup reference
<form novalidate>
<label for="email">Email</label>
<input id="email" name="email" type="email" required
pattern="[^@]+@[^@]+\.[^@]+">
<select name="plan">
<option value="free">Free</option>
<option value="pro" selected>Pro</option>
</select>
<textarea name="msg" rows="4" maxlength="500"></textarea>
<fieldset>
<legend>Level</legend>
<input type="radio" name="level" value="beginner" checked>
<input type="radio" name="level" value="advanced">
</fieldset>
<button type="submit">Send</button>
</form>Class structure and instantiation
public class Car {
private String model;
public Car(String model) {
this.model = model;
}
public String getModel() {
return model;
}
public static void main(String[] args) {
Car tesla = new Car("Model 3");
System.out.println(tesla.getModel());
}
}Exception handling and try-with-resources
try {
int result = 10 / Integer.parseInt(input);
} catch (ArithmeticException e) {
System.err.println("division by zero");
} catch (NumberFormatException e) {
System.err.println("bad number: " + e.getMessage());
} finally {
closeResources();
}
// Try-with-resources
try (BufferedReader reader = new BufferedReader(new FileReader("f.txt"))) {
System.out.println(reader.readLine());
}Loop styles and control flow
int[] nums = {1, 2, 3};
for (int i = 0; i < nums.length; i++) { }
for (int n : nums) { } // enhanced for
List<String> names = new ArrayList<>(List.of("a", "b"));
names.forEach(System.out::println);
for (int i = 0; i < 10; i++) {
if (i == 3) continue;
if (i == 8) break;
}Properties, auto-props, and expression bodies
public class Product {
public string Name { get; set; }
public decimal Price { get; private set; } = 0m;
public Product(string name, decimal price) {
Name = name;
Price = price;
}
public decimal Total(int qty) => Price * qty;
}
var p = new Product("Keyboard", 49.99m);
Console.WriteLine(p.Total(2)); // 99.98Async/await patterns and Task composition
public async Task<string> FetchAsync(HttpClient client, string url)
{
var response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
// Fire-and-forget
_ = SomeLongTaskAsync();
// Parallel
var tasks = urls.Select(u => FetchAsync(client, u));
var results = await Task.WhenAll(tasks);Encapsulation with member functions
class BankAccount {
private:
double balance = 0.0;
public:
BankAccount(double initial) : balance(initial) {}
void deposit(double amount) { balance += amount; }
double getBalance() const { return balance; }
};
int main() {
BankAccount account(100.0);
account.deposit(50.0);
std::cout << account.getBalance() << std::endl;
}Modern C++ iteration and algorithms
#include <algorithm>
#include <numeric>
std::vector<int> v = {3, 1, 4, 1, 5};
for (const auto& x : v) // range-based
std::cout << x << " ";
std::sort(v.begin(), v.end());
int total = std::accumulate(v.begin(), v.end(), 0);
auto is_even = [](int n) { return n % 2 == 0; };
int evens = std::count_if(v.begin(), v.end(), is_even);