- Регистрация
- 1 Мар 2015
- Сообщения
- 1,481
- Баллы
- 155
Introduction
If you’re a JavaScript developer diving into Python, you’ll find many concepts familiar but with syntactic twists. Python’s emphasis on readability and simplicity means fewer brackets, strict indentation, and a different approach to common tasks. Let’s break down key differences with side-by-side examples.
1. Variables and Constants
JavaScript
let mutableVar = 10; // Mutable
const immutableVar = 20; // Immutable
Python
mutable_var = 10 # No 'let' or 'const'—all variables are mutable
IMMUTABLE_VAR = 20 # Convention: UPPER_CASE for "constants" (not enforced)
Key Notes:
3. Conditionals
JavaScript
if (age > 18) {
console.log("Adult");
} else if (age === 18) {
console.log("Exactly 18");
} else {
console.log("Minor");
}
Python
if age > 18:
print("Adult")
elif age == 18: # 'elif' instead of 'else if'
print("Exactly 18")
else:
print("Minor") # Indentation defines blocks (no curly braces!)
Gotchas:
For Loop
JavaScript (C-style):
for (let i = 0; i < 5; i++) {
console.log(i);
}
Python (range-based):
for i in range(5): # range(0, 5) → 0,1,2,3,4
print(i)
Iterating Over Arrays/Lists
JavaScript:
const fruits = ["apple", "banana"];
for (const fruit of fruits) {
console.log(fruit);
}
Python:
fruits = ["apple", "banana"]
for fruit in fruits:
print(fruit)
5. Functions
JavaScript
function multiply(a, b) {
return a * b;
}
// Arrow function
const multiply = (a, b) => a * b;
Python
def multiply(a, b):
return a * b
# Lambda (anonymous)
multiply = lambda a, b: a * b
Key Differences:
Template Literals (JS) vs. f-Strings (Python)
JavaScript:
const name = "Alice";
console.log(`Hello, ${name}!`); // Backticks
Python:
name = "Alice"
print(f"Hello, {name}!") # 'f' prefix
7. Arrays (JS) vs. Lists (Python)
Python List Comprehension Example:
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
8. Objects (JS) vs. Dictionaries (Python)
JavaScript:
const user = {
name: "Alice",
age: 30
};
console.log(user.name); // Dot notation
Python:
user = {
"name": "Alice",
"age": 30
}
print(user["name"]) # Or user.get("name")
9. Classes
JavaScript
class Dog {
constructor(name) {
this.name = name;
}
bark() {
console.log("Woof!");
}
}
Python
class Dog:
def __init__(self, name): # Constructor
self.name = name
def bark(self): # 'self' is explicit
print("Woof!")
Key Notes:
JavaScript:
try {
throw new Error("Failed!");
} catch (error) {
console.log(error.message);
}
Python:
try:
raise Exception("Failed!")
except Exception as e:
print(e)
11. Modules and Imports
JavaScript (ES6):
import React from 'react';
export const PI = 3.14;
Python:
import math
from math import sqrt
# Exporting: Just write variables/functions in the file.
PI = 3.14
12. Truthy and Falsy Values
Example:
if not []: # Empty list is falsy
print("This list is empty!")
Key Takeaways
JavaScript:
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
Python:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
Next Steps
Python’s syntax feels minimalist compared to JavaScript, but its strict structure encourages clean code. Start small, embrace indentation, and leverage Python’s powerful built-in tools.
Happy coding! ?
Author: Mohin Sheikh
Follow me on for more insights!
If you’re a JavaScript developer diving into Python, you’ll find many concepts familiar but with syntactic twists. Python’s emphasis on readability and simplicity means fewer brackets, strict indentation, and a different approach to common tasks. Let’s break down key differences with side-by-side examples.
1. Variables and Constants
JavaScript
let mutableVar = 10; // Mutable
const immutableVar = 20; // Immutable
Python
mutable_var = 10 # No 'let' or 'const'—all variables are mutable
IMMUTABLE_VAR = 20 # Convention: UPPER_CASE for "constants" (not enforced)
Key Notes:
- Python uses snake_case (not camelCase).
- No var or const—just assign values.
| JavaScript | Python | Notes |
|---|---|---|
| number | int, float | Python distinguishes integers and floats. |
| string | str | Both use template literals/f-strings. |
| boolean (lowercase) | bool (TitleCase) | Python: True/False (case-sensitive). |
| array | list, tuple | Lists are mutable; tuples are immutable. |
| object | dict | Python dicts ≈ JS objects. |
| null/undefined | None | Python’s universal "no value" placeholder. |
JavaScript
if (age > 18) {
console.log("Adult");
} else if (age === 18) {
console.log("Exactly 18");
} else {
console.log("Minor");
}
Python
if age > 18:
print("Adult")
elif age == 18: # 'elif' instead of 'else if'
print("Exactly 18")
else:
print("Minor") # Indentation defines blocks (no curly braces!)
Gotchas:
- Use == for equality checks (Python has no ===).
- Indentation is mandatory—use 4 spaces (no tabs).
For Loop
JavaScript (C-style):
for (let i = 0; i < 5; i++) {
console.log(i);
}
Python (range-based):
for i in range(5): # range(0, 5) → 0,1,2,3,4
print(i)
Iterating Over Arrays/Lists
JavaScript:
const fruits = ["apple", "banana"];
for (const fruit of fruits) {
console.log(fruit);
}
Python:
fruits = ["apple", "banana"]
for fruit in fruits:
print(fruit)
5. Functions
JavaScript
function multiply(a, b) {
return a * b;
}
// Arrow function
const multiply = (a, b) => a * b;
Python
def multiply(a, b):
return a * b
# Lambda (anonymous)
multiply = lambda a, b: a * b
Key Differences:
- Python uses def instead of function.
- Lambdas are limited to single expressions.
Template Literals (JS) vs. f-Strings (Python)
JavaScript:
const name = "Alice";
console.log(`Hello, ${name}!`); // Backticks
Python:
name = "Alice"
print(f"Hello, {name}!") # 'f' prefix
7. Arrays (JS) vs. Lists (Python)
| Action | JavaScript | Python |
|---|---|---|
| Add element | arr.push(4) | lst.append(4) |
| Remove last | arr.pop() | lst.pop() |
| Check existence | arr.includes(4) | 4 in lst |
| Create copy | [...arr] | lst.copy() |
| Map | arr.map(x => x*2) | [x*2 for x in lst] |
Python List Comprehension Example:
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
8. Objects (JS) vs. Dictionaries (Python)
JavaScript:
const user = {
name: "Alice",
age: 30
};
console.log(user.name); // Dot notation
Python:
user = {
"name": "Alice",
"age": 30
}
print(user["name"]) # Or user.get("name")
9. Classes
JavaScript
class Dog {
constructor(name) {
this.name = name;
}
bark() {
console.log("Woof!");
}
}
Python
class Dog:
def __init__(self, name): # Constructor
self.name = name
def bark(self): # 'self' is explicit
print("Woof!")
Key Notes:
- Python requires self as the first method parameter.
- No new keyword: my_dog = Dog("Buddy").
JavaScript:
try {
throw new Error("Failed!");
} catch (error) {
console.log(error.message);
}
Python:
try:
raise Exception("Failed!")
except Exception as e:
print(e)
11. Modules and Imports
JavaScript (ES6):
import React from 'react';
export const PI = 3.14;
Python:
import math
from math import sqrt
# Exporting: Just write variables/functions in the file.
PI = 3.14
12. Truthy and Falsy Values
| JavaScript Falsy | Python Falsy |
|---|---|
| false, 0, "" | False, 0, "" |
| null, undefined | None |
| NaN | [], {}, () |
Example:
if not []: # Empty list is falsy
print("This list is empty!")
Key Takeaways
- Indentation Rules: Python uses indentation (4 spaces) instead of curly braces.
- Simplicity: Python favors explicit, readable code (e.g., elif over else if).
- Rich Data Structures: Lists, tuples, sets, and dictionaries offer flexibility.
- No Semicolons: Optional in Python (but avoid them).
JavaScript:
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
Python:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
Next Steps
- Practice: Use platforms like to solve problems in Python.
- Explore Libraries: Learn numpy (arrays), pandas (dataframes), and requests (HTTP).
- Read the Zen of Python: Run import this in a Python shell.
Python’s syntax feels minimalist compared to JavaScript, but its strict structure encourages clean code. Start small, embrace indentation, and leverage Python’s powerful built-in tools.
Happy coding! ?
Author: Mohin Sheikh
Follow me on for more insights!