Skip to main content

📋 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 outputprint("Hello")console.log("Hello")Console.WriteLine("Hello")
Read inputinput("Name: ")readline (Node.js)Console.ReadLine()
Comments# single line// single line// single line
Multi-line comment"""docstring"""/* block *//* block */
Line endingNewline (no semicolons); (optional); (required)
Code blocksIndentation{ }{ }
Run a filepython file.pynode file.jsdotnet run

Variables & Constants

Operation🐍 Python⚡ JavaScript🔷 C#
Declare variablex = 10let x = 10;int x = 10;
ConstantMAX = 100 (convention)const MAX = 100;const int MAX = 100;
Type inferenceAlways (dynamic)Always (dynamic)var x = 10;
Null / NoneNonenull / undefinednull
Check nullx is Nonex === nullx == null or x is null
Type checktype(x)typeof xx.GetType()

Data Types

Type🐍 Python⚡ JavaScript🔷 C#
Integerint42number42int42
Float / Decimalfloat3.14number3.14double3.14
Stringstr"hi"string"hi"string"hi"
BooleanTrue / Falsetrue / falsetrue / false
Convert to intint("42")parseInt("42")int.Parse("42")
Convert to stringstr(42)String(42)42.ToString()
Convert to floatfloat("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 interpolationf"Hello, {name}"`Hello, ${name}`$"Hello, {name}"
Concatenation"Hi " + name"Hi " + name"Hi " + name
Lengthlen(s)s.lengths.Length
Uppercases.upper()s.toUpperCase()s.ToUpper()
Lowercases.lower()s.toLowerCase()s.ToLower()
Trim whitespaces.strip()s.trim()s.Trim()
Contains"lo" in ss.includes("lo")s.Contains("lo")
Splits.split(",")s.split(",")s.Split(',')
Replaces.replace("a", "b")s.replace("a", "b")s.Replace("a", "b")
Substring / Slices[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!=!==!=
Andand&&&&
Oror||||
Notnot!!

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}
Accessitems[0]items[0]items[0]
Lengthlen(items)items.lengthitems.Count
Additems.append(x)items.push(x)items.Add(x)
Removeitems.remove(x)items.splice(i, 1)items.Remove(x)
Find indexitems.index(x)items.indexOf(x)items.IndexOf(x)
Containsx in itemsitems.includes(x)items.Contains(x)
Sortitems.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}}
Accessd["key"]obj.key or obj["key"]d["key"]
Safe accessd.get("key", default)obj?.key ?? defaultd.TryGetValue("key", out val)
Set valued["key"] = valobj.key = vald["key"] = val
Deletedel d["key"]delete obj.keyd.Remove("key")
Keysd.keys()Object.keys(obj)d.Keys
Valuesd.values()Object.values(obj)d.Values
Contains key"key" in d"key" in objd.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 fileopen(f).read()fs.readFileSync(f,"utf-8")File.ReadAllText(f)
Write fileopen(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 JSONjson.loads(s)JSON.parse(s)JsonSerializer.Deserialize<T>(s)
To JSON stringjson.dumps(obj)JSON.stringify(obj)JsonSerializer.Serialize(obj)
Pretty JSONjson.dumps(obj, indent=2)JSON.stringify(obj, null, 2)new JsonSerializerOptions {WriteIndented=true}

API Requests

Operation🐍 Python⚡ JavaScript🔷 C#
HTTP libraryrequests (pip install)fetch() (built-in)HttpClient (built-in)
GET requestrequests.get(url)await fetch(url)await client.GetAsync(url)
Parse JSONresponse.json()await response.json()JsonDocument.Parse(text)
Status coderesponse.status_coderesponse.status(int)response.StatusCode
Success checkstatus_code == 200response.okresponse.IsSuccessStatusCode
Query paramsparams={...}URLSearchParamsHttpUtility.ParseQueryString
Env variableos.environ.get(key)process.env.KEYEnvironment.GetEnvironmentVariable