I'll guide you through Python fundamentals by comparing concepts with JavaScript. Let's start!
1. Hello World & Basic Syntax
JavaScript
console.log("Hello World");
let x = 5;
Python
print("Hello World")
x = 5 # No semicolon, no let/const
Key Differences:
- No semicolons in Python
- Indentation matters (replaces curly braces)
- Comments use
#instead of//
2. Variables & Data Types
JavaScript
let name = "Alice"; // string
let age = 30; // number
let isStudent = true; // boolean
let scores = [95, 87, 91]; // array
let person = { // object
name: "Bob",
age: 25
};
let nothing = null;
let notDefined = undefined;
Python
name = "Alice" # str
age = 30 # int (or float for decimals)
is_student = True # bool (capital T/F)
scores = [95, 87, 91] # list (mutable)
person = { # dict (dictionary)
"name": "Bob",
"age": 25
}
nothing = None # Python's null/undefined
Key Differences:
- Python uses snake_case (not camelCase)
-
True/Falsecapitalized -
Noneinstead ofnull/undefined - Lists ≈ Arrays, Dicts ≈ Objects
3. Control Flow
JavaScript
// If-else
if (age >= 18) {
console.log("Adult");
} else if (age >= 13) {
console.log("Teen");
} else {
console.log("Child");
}
// For loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// While loop
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
Python
# If-else (indentation instead of braces)
if age >= 18:
print("Adult")
elif age >= 13: # NOT else if
print("Teen")
else:
print("Child")
# For loop (more like for...of in JS)
for i in range(5): # range(5) = [0, 1, 2, 3, 4]
print(i)
# Iterate over list (like for...of)
for score in scores:
print(score)
# While loop
count = 0
while count < 5:
print(count)
count += 1 # No ++ operator in Python
4. Functions
JavaScript
// Function declaration
function add(a, b) {
return a + b;
}
// Arrow function
const multiply = (a, b) => a * b;
// Default parameters
function greet(name = "Guest") {
return `Hello ${name}`;
}
Python
# Function definition (def instead of function)
def add(a, b):
return a + b # Indented body
# Lambda functions ≈ Arrow functions
multiply = lambda a, b: a * b
# Default parameters
def greet(name="Guest"):
return f"Hello {name}" # f-strings like template literals
# Multiple return values (tuples)
def get_coordinates():
return 10, 20 # Returns a tuple (10, 20)
x, y = get_coordinates() # Destructuring assignment
5. Data Structures Comparison
Arrays/Lists
// JavaScript Arrays
let arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // [1, 2, 3]
let sliced = arr.slice(0, 2); // [1, 2]
# Python Lists
arr = [1, 2, 3]
arr.append(4) # [1, 2, 3, 4]
arr.pop() # [1, 2, 3] (removes last)
sliced = arr[0:2] # [1, 2] (slicing syntax)
arr.insert(1, 99) # [1, 99, 2, 3]
# List comprehension (unique to Python)
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
Objects/Dictionaries
// JavaScript Objects
let person = {
name: "Alice",
age: 30,
greet() {
return `Hello, I'm ${this.name}`;
}
};
console.log(person.name);
console.log(person["age"]);
# Python Dictionaries
person = {
"name": "Alice",
"age": 30,
"greet": lambda self: f"Hello, I'm {self['name']}"
}
print(person["name"]) # Access with brackets
print(person.get("age")) # Safer access
# Methods don't naturally have 'this' context
# Usually you'd use classes for that (see below)
6. Classes & OOP
JavaScript (ES6+)
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, I'm ${this.name}`;
}
static species = "Human";
}
const alice = new Person("Alice", 30);
Python
class Person:
species = "Human" # Class attribute (static)
def __init__(self, name, age): # Constructor
self.name = name # Instance attribute
self.age = age
def greet(self): # Methods always have self parameter
return f"Hello, I'm {self.name}"
@staticmethod
def static_method():
return "This is static"
alice = Person("Alice", 30)
print(alice.greet()) # No parentheses needed for self when calling
7. Modules & Imports
JavaScript (ES6 Modules)
// math.js
export const PI = 3.14159;
export function add(a, b) { return a + b; }
// main.js
import { PI, add } from './math.js';
import * as math from './math.js';
Python
# math.py
PI = 3.14159
def add(a, b):
return a + b
# main.py
from math import PI, add
import math # Then use math.PI, math.add
import math as m # Alias
8. Error Handling
JavaScript
try {
throw new Error("Something went wrong");
} catch (error) {
console.error(error.message);
} finally {
console.log("Cleanup");
}
Python
try:
raise Exception("Something went wrong")
except Exception as e: # 'as' instead of variable declaration
print(f"Error: {e}")
finally:
print("Cleanup")
9. Async Programming
JavaScript (Promises/Async-Await)
// Promise
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
// Async/await
async function getData() {
const response = await fetch(url);
return await response.json();
}
Python (Async/Await)
import asyncio
import aiohttp # External library for HTTP
async def fetch_data(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.json()
# Run async function
asyncio.run(fetch_data('https://api.example.com/data'))
10. Common Patterns & Tips
1. Type Checking (Python is dynamically typed but has type hints)
def add(a: int, b: int) -> int: # Type hints (optional)
return a + b
2. String Formatting (multiple ways)
name = "Alice"
# f-strings (Python 3.6+, like template literals)
print(f"Hello {name}")
# .format() method
print("Hello {}".format(name))
# % formatting (older style)
print("Hello %s" % name)
3. Tuple vs List
# List - mutable
my_list = [1, 2, 3]
my_list[0] = 99 # OK
# Tuple - immutable
my_tuple = (1, 2, 3)
# my_tuple[0] = 99 # ERROR!
4. Sets (unique unordered collection)
my_set = {1, 2, 3, 3, 2} # {1, 2, 3} (duplicates removed)
another_set = set([1, 2, 3, 4]) # Alternative creation
Quick Reference Table
| JavaScript | Python | Notes |
|---|---|---|
let x = 5; |
x = 5 |
No declaration keywords |
const arr = [] |
arr = [] |
No const, just assign |
null / undefined
|
None |
Single null value |
=== strict equality |
== and is
|
== value, is identity |
array.length |
len(list) |
Function, not property |
array.map() |
List comprehensions | [x*2 for x in arr] |
for (let i=0; i<n; i++) |
for i in range(n) |
Different pattern |
function fn() {} |
def fn(): |
def keyword |
obj.property |
dict["key"] or obj.attr
|
Depends on type |
class MyClass {} |
class MyClass: |
Colon and indentation |
Practice Exercise
Convert this JavaScript code to Python:
function filterEvenSquares(numbers) {
return numbers
.filter(n => n % 2 === 0)
.map(n => n ** 2);
}
const result = filterEvenSquares([1, 2, 3, 4, 5]);
console.log(result); // [4, 16]
Python solution:
def filter_even_squares(numbers):
return [n**2 for n in numbers if n % 2 == 0]
result = filter_even_squares([1, 2, 3, 4, 5])
print(result) # [4, 16]
Next Steps
- Install Python and a good IDE (VS Code with Python extension works well)
- Practice by rewriting your JS projects in Python
- Explore Python-specific features: decorators, generators, context managers
-
Learn popular libraries:
- Web: Flask/Django (Express equivalents)
- Data: NumPy, Pandas
- AI/ML: TensorFlow, PyTorch
The main mindset shift: Python emphasizes readability and simplicity over cleverness. You'll write less code to accomplish the same tasks!
Top comments (0)