📋 Syntax Cheat Sheet
Your Rosetta Stone for Python, JavaScript, and C#. Bookmark this page — you'll come back to it constantly.
📑 Jump To
Basics & Output
| Operation | 🐍 Python | ⚡ JavaScript | 🔷 C# |
|---|---|---|---|
| Print output | print("Hello") | console.log("Hello") | Console.WriteLine("Hello") |
| Read input | input("Name: ") | readline (Node.js) | Console.ReadLine() |
| Comments | # single line | // single line | // single line |
| Multi-line comment | """docstring""" | /* block */ | /* block */ |
| Line ending | Newline (no semicolons) | ; (optional) | ; (required) |
| Code blocks | Indentation | { } | { } |
| Run a file | python file.py | node file.js | dotnet run |
Variables & Constants
| Operation | 🐍 Python | ⚡ JavaScript | 🔷 C# |
|---|---|---|---|
| Declare variable | x = 10 | let x = 10; | int x = 10; |
| Constant | MAX = 100 (convention) | const MAX = 100; | const int MAX = 100; |
| Type inference | Always (dynamic) | Always (dynamic) | var x = 10; |
| Null / None | None | null / undefined | null |
| Check null | x is None | x === null | x == null or x is null |
| Type check | type(x) | typeof x | x.GetType() |
Data Types
| Type | 🐍 Python | ⚡ JavaScript | 🔷 C# |
|---|---|---|---|
| Integer | int → 42 | number → 42 | int → 42 |
| Float / Decimal | float → 3.14 | number → 3.14 | double → 3.14 |
| String | str → "hi" | string → "hi" | string → "hi" |
| Boolean | True / False | true / false | true / false |
| Convert to int | int("42") | parseInt("42") | int.Parse("42") |
| Convert to string | str(42) | String(42) | 42.ToString() |
| Convert to float | float("3.14") | parseFloat("3.14") | double.Parse("3.14") |
⚠️ Python Gotcha
Python booleans are capitalized: True and False (not true/false). This trips up everyone coming from JS or C#.
Strings & Interpolation
| Operation | 🐍 Python | ⚡ JavaScript | 🔷 C# |
|---|---|---|---|
| String interpolation | f"Hello, {name}" | `Hello, ${name}` | $"Hello, {name}" |
| Concatenation | "Hi " + name | "Hi " + name | "Hi " + name |
| Length | len(s) | s.length | s.Length |
| Uppercase | s.upper() | s.toUpperCase() | s.ToUpper() |
| Lowercase | s.lower() | s.toLowerCase() | s.ToLower() |
| Trim whitespace | s.strip() | s.trim() | s.Trim() |
| Contains | "lo" in s | s.includes("lo") | s.Contains("lo") |
| Split | s.split(",") | s.split(",") | s.Split(',') |
| Replace | s.replace("a", "b") | s.replace("a", "b") | s.Replace("a", "b") |
| Substring / Slice | s[1:4] | s.slice(1, 4) | s.Substring(1, 3) |
| Multi-line string | """multi\nline""" | `multi\nline` | @"multi\nline" |
Conditionals
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
# Ternary
result = "pass" if score >= 60 else "fail"
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else {
grade = "C";
}
// Ternary
const result = score >= 60 ? "pass" : "fail";
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else {
grade = "C";
}
// Ternary
string result = score >= 60 ? "pass" : "fail";
| Operator | 🐍 Python | ⚡ JavaScript | 🔷 C# |
|---|---|---|---|
| Equals | == | === (strict) | == |
| Not equals | != | !== | != |
| And | and | && | && |
| Or | or | || | || |
| Not | not | ! | ! |
Loops
# For loop (range)
for i in range(5): # 0, 1, 2, 3, 4
print(i)
# For loop (over collection)
for item in items:
print(item)
# For loop (with index)
for i, item in enumerate(items):
print(f"{i}: {item}")
# While loop
while count < 10:
count += 1
# Break and continue
for x in items:
if x == "skip": continue
if x == "stop": break
// For loop (classic)
for (let i = 0; i < 5; i++) {
console.log(i);
}
// For...of (over collection)
for (const item of items) {
console.log(item);
}
// forEach (with index)
items.forEach((item, i) => {
console.log(`${i}: ${item}`);
});
// While loop
while (count < 10) {
count++;
}
// Break and continue work the same
// For loop (classic)
for (int i = 0; i < 5; i++) {
Console.WriteLine(i);
}
// Foreach (over collection)
foreach (var item in items) {
Console.WriteLine(item);
}
// For loop with index
for (int i = 0; i < items.Count; i++) {
Console.WriteLine($"{i}: {items[i]}");
}
// While loop
while (count < 10) {
count++;
}
// Break and continue work the same
Functions
# Basic function
def greet(name):
return f"Hello, {name}!"
# Default parameters
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
# Multiple return values
def divide(a, b):
return a // b, a % b
quotient, remainder = divide(17, 5)
# Lambda
double = lambda x: x * 2
// Basic function
function greet(name) {
return `Hello, ${name}!`;
}
// Default parameters
function greet(name, greeting = "Hello") {
return `${greeting}, ${name}!`;
}
// Arrow function
const double = (x) => x * 2;
// Async function
async function fetchData(url) {
const res = await fetch(url);
return await res.json();
}
// Basic method
static string Greet(string name) {
return $"Hello, {name}!";
}
// Default parameters
static string Greet(string name, string greeting = "Hello") {
return $"{greeting}, {name}!";
}
// Expression body
static int Double(int x) => x * 2;
// Void (no return value)
static void PrintMessage(string msg) {
Console.WriteLine(msg);
}
// Async method
static async Task<string> FetchData(string url) {
return await client.GetStringAsync(url);
}
Collections
| Operation | 🐍 Python (list) | ⚡ JS (Array) | 🔷 C# (List<T>) |
|---|---|---|---|
| Create | [1, 2, 3] | [1, 2, 3] | new List<int> {1, 2, 3} |
| Access | items[0] | items[0] | items[0] |
| Length | len(items) | items.length | items.Count |
| Add | items.append(x) | items.push(x) | items.Add(x) |
| Remove | items.remove(x) | items.splice(i, 1) | items.Remove(x) |
| Find index | items.index(x) | items.indexOf(x) | items.IndexOf(x) |
| Contains | x in items | items.includes(x) | items.Contains(x) |
| Sort | items.sort() | items.sort() | items.Sort() |
| Filter | [x for x in items if x > 5] | items.filter(x => x > 5) | items.Where(x => x > 5) |
| Map / Transform | [x * 2 for x in items] | items.map(x => x * 2) | items.Select(x => x * 2) |
| Operation | 🐍 Python (dict) | ⚡ JS (Object / Map) | 🔷 C# (Dictionary) |
|---|---|---|---|
| Create | {"a": 1, "b": 2} | {a: 1, b: 2} | new Dictionary<string,int> {{"a",1}} |
| Access | d["key"] | obj.key or obj["key"] | d["key"] |
| Safe access | d.get("key", default) | obj?.key ?? default | d.TryGetValue("key", out val) |
| Set value | d["key"] = val | obj.key = val | d["key"] = val |
| Delete | del d["key"] | delete obj.key | d.Remove("key") |
| Keys | d.keys() | Object.keys(obj) | d.Keys |
| Values | d.values() | Object.values(obj) | d.Values |
| Contains key | "key" in d | "key" in obj | d.ContainsKey("key") |
Classes & OOP
class Animal:
def __init__(self, name, sound):
self.name = name
self.sound = sound
def speak(self):
return f"{self.name} says {self.sound}!"
def __str__(self):
return f"Animal({self.name})"
class Dog(Animal): # Inheritance
def __init__(self, name):
super().__init__(name, "Woof")
def speak(self): # Override
return f"{self.name} barks loudly!"
dog = Dog("Rex")
print(dog.speak())
class Animal {
constructor(name, sound) {
this.name = name;
this.sound = sound;
}
speak() {
return `${this.name} says ${this.sound}!`;
}
toString() {
return `Animal(${this.name})`;
}
}
class Dog extends Animal { // Inheritance
constructor(name) {
super(name, "Woof");
}
speak() { // Override
return `${this.name} barks loudly!`;
}
}
const dog = new Dog("Rex");
console.log(dog.speak());
class Animal {
public string Name { get; set; }
public string Sound { get; set; }
public Animal(string name, string sound) {
Name = name; Sound = sound;
}
public virtual string Speak() // virtual = overridable
=> $"{Name} says {Sound}!";
public override string ToString()
=> $"Animal({Name})";
}
class Dog : Animal { // Inheritance
public Dog(string name) : base(name, "Woof") { }
public override string Speak() // Override
=> $"{Name} barks loudly!";
}
var dog = new Dog("Rex");
Console.WriteLine(dog.Speak());
Error Handling
try:
result = int(input("Number: "))
print(10 / result)
except ValueError:
print("Not a number!")
except ZeroDivisionError:
print("Can't divide by zero!")
except Exception as e:
print(f"Error: {e}")
finally:
print("Always runs")
# Raise an exception
raise ValueError("Invalid input")
try {
const num = parseInt(input);
if (isNaN(num)) throw new Error("Not a number!");
console.log(10 / num);
} catch (err) {
console.log(`Error: ${err.message}`);
} finally {
console.log("Always runs");
}
// Throw an error
throw new Error("Invalid input");
try {
int num = int.Parse(Console.ReadLine()!);
Console.WriteLine(10 / num);
}
catch (FormatException) {
Console.WriteLine("Not a number!");
}
catch (DivideByZeroException) {
Console.WriteLine("Can't divide by zero!");
}
catch (Exception ex) {
Console.WriteLine($"Error: {ex.Message}");
}
finally {
Console.WriteLine("Always runs");
}
// Throw an exception
throw new ArgumentException("Invalid input");
File I/O & JSON
| Operation | 🐍 Python | ⚡ JavaScript (Node) | 🔷 C# |
|---|---|---|---|
| Read file | open(f).read() | fs.readFileSync(f,"utf-8") | File.ReadAllText(f) |
| Write file | open(f,"w").write(s) | fs.writeFileSync(f, s) | File.WriteAllText(f, s) |
| File exists? | os.path.exists(f) | fs.existsSync(f) | File.Exists(f) |
| Parse JSON | json.loads(s) | JSON.parse(s) | JsonSerializer.Deserialize<T>(s) |
| To JSON string | json.dumps(obj) | JSON.stringify(obj) | JsonSerializer.Serialize(obj) |
| Pretty JSON | json.dumps(obj, indent=2) | JSON.stringify(obj, null, 2) | new JsonSerializerOptions {WriteIndented=true} |
API Requests
| Operation | 🐍 Python | ⚡ JavaScript | 🔷 C# |
|---|---|---|---|
| HTTP library | requests (pip install) | fetch() (built-in) | HttpClient (built-in) |
| GET request | requests.get(url) | await fetch(url) | await client.GetAsync(url) |
| Parse JSON | response.json() | await response.json() | JsonDocument.Parse(text) |
| Status code | response.status_code | response.status | (int)response.StatusCode |
| Success check | status_code == 200 | response.ok | response.IsSuccessStatusCode |
| Query params | params={...} | URLSearchParams | HttpUtility.ParseQueryString |
| Env variable | os.environ.get(key) | process.env.KEY | Environment.GetEnvironmentVariable |