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; });