How To Learn Python For JavaScript Developers (Full Handbook)
How To Learn Python For JavaScript Developers (Full Handbook)
But while JavaScript is powerful, there are other languages that shine
in specific areas where JavaScript may not be the most efficient
choice. One of those languages is Python.
Table of Contents
1. Brief Overview of JavaScript and Python
7. Asynchronous Programming
13. Conclusion
JavaScript is event-driven, and it’s often praised for its versatility and
asynchronous capabilities, which are essential for building modern,
responsive web applications.
3. Versatile Applications
While JavaScript dominates web development, Python is
widely used in fields like automation, web scraping, and
scientific computing. For example, if you’re looking to
automate repetitive tasks, Python provides a straightforward
approach with powerful libraries like os , shutil , and sys for Donate
Forum
system operations. In web scraping, libraries like
Learn to code — free 3,000-hour curriculum
BeautifulSoup and Scrapy make data extraction a breeze.
JavaScript
Known primarily as the language of the web, JavaScript was originally
designed to add interactivity to HTML documents within browsers.
Today, with the advent of frameworks like React, Angular, and Vue,
JavaScript is at the core of modern, interactive frontend web
development.
Python
Initially created with a focus on readability and simplicity, Python has
become one of the most versatile languages in the world. While
JavaScript is often tied to web applications, Python is more commonly
used in fields like scientific computing, data analysis, machine learning,
and artificial intelligence. Its readability and simplicity make it a great
choice for scripting, automation, and rapid prototyping.
print("Hello, World!")
JavaScript:
console.log("Hello, World!");
Python:
for i in range(5):
print(i)
JavaScript:
Variable Declaration
JavaScript requires let , const , or var to declare variables. The use
of let and const in modern JavaScript helps manage scope and
constancy of variables, with const enforcing immutability.
JavaScript:
Python:
age = 25 # Python infers type automatically
Forum Donate
name = "Alice" # No need to declare as const or let
Learn to code — free 3,000-hour curriculum
JavaScript:
Python:
Python does not allow implicit type coercion, reducing potential bugs
related to unexpected type behavior. If type conversion is needed,
Python requires explicit casting.
Python:
Forum Donate
my_list = [1, "apple", 3.14]
Learn to code — free 3,000-hour curriculum
JavaScript:
Tuples
Python offers tuple as an immutable version of a list, useful when
data should not be modified. JavaScript has no direct equivalent,
though const can create a similar effect by enforcing immutability.
Python:
Sets
Both languages offer a set data type for collections of unique
elements. Python has set , while JavaScript uses Set .
Python:
my_set = {1, 2, 3}
JavaScript: Forum Donate
Python:
JavaScript:
JavaScript:
Loops
For Loops: Python’s for loop is often simpler, especially with
the range() function. JavaScript’s traditional for loop has
more structure but allows for flexibility.
Python:
for i in range(5):
Forum Donate
print(i)
Learn to code — free 3,000-hour curriculum
JavaScript:
Python:
count = 0
while count < 5:
print(count)
count += 1
JavaScript:
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
Forum Donate
Key Takeaways:
Learn to code — free 3,000-hour curriculum
Python’s syntax is minimalist and requires indentation, which
encourages clean, readable code.
Python has built-in data structures like lists, tuples, sets, and
dictionaries, each with specific use cases, while JavaScript
relies on arrays and objects.
They can store any type of data, including other lists, making
them useful for nested data structures.
JavaScript Arrays:
Python:
JavaScript:
// Creating and manipulating an array
Forum Donate
let myArray = [1, 2, 3];
Learn to code — free 3,000-hour curriculum
myArray.push(4); // Adds 4 to the end
myArray.splice(1, 0, 10); // Inserts 10 at index 1
myArray.splice(myArray.indexOf(2), 1); // Removes the first occurre
console.log(myArray); // Output: [1, 10, 3, 4]
Python’s list functions are often simpler and more intuitive, which is
particularly beneficial for quick data manipulation.
Tuples
Python offers tuples as an immutable sequence type, meaning their
elements cannot be changed once created. Tuples are useful when you
need a sequence of items that should remain constant throughout the
program’s execution.
Python Tuple:
my_tuple = (1, 2, 3)
# Attempting to modify will raise an error:
# my_tuple[0] = 10 # Raises TypeError
Sets
Both JavaScript and Python offer sets as a way to store unique
Forum values.
Donate
Sets are unordered and do not allow duplicates, making them ideal for
Learn to code — free 3,000-hour curriculum
collections where each item should be unique.
Python Sets:
JavaScript Sets:
Python:
JavaScript:
Forum Donate
// Creating and using a set
let fruits = new Set(["apple", "banana", "cherry"]);
Learn to code — free 3,000-hour curriculum
fruits.add("orange"); // Adds "orange" to the set
fruits.delete("banana"); // Removes "banana" from the set
console.log(fruits); // Output: Set { "apple", "cherry",
Python:
JavaScript:
Python:
import json
Forum Donate
JavaScript:
Key Takeaways:
Lists and Arrays: Python’s lists are versatile and come with
built-in manipulation methods. JavaScript arrays are flexible
but less concise in syntax.
JavaScript Functions:
In JavaScript, functions can be defined in several ways: using the
function keyword, as an arrow function ( => ), or as a method within
an object. Modern JavaScript commonly uses arrow functions for their
brevity and lexical this behavior.
Example: Basic Function Definition Forum Donate
def greet(name):
return f"Hello, {name}!"
JavaScript:
function greet(name) {
return `Hello, ${name}!`;
}
Key Differences:
x = "global"
def outer_function():
x = "enclosing"
def inner_function():
x = "local"
print(x)
inner_function()
outer_function() # Output: local
Forum Donate
print(x) # Output: global
JavaScript Closures:
JavaScript handles scope using function-level and block-level scoping.
Variables declared with let and const have block scope, while var
has function scope.
function outerFunction() {
let x = "enclosing";
function innerFunction() {
let x = "local";
console.log(x);
}
innerFunction();
}
Key Differences:
square = lambda x: x ** 2
print(square(5)) # Output: 25
Key Differences:
Key Takeaways:
Python’s function syntax ( def ) is straightforward and
emphasizes readability, while JavaScript offers flexibility with
function , arrow functions, and method definitions.
6. Object-Oriented Programming
(OOP)
Object-Oriented Programming (OOP) allows developers to create
reusable and modular code by encapsulating data and behavior into
objects. Both Python and JavaScript support OOP, but they implement
it differently.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
class Dog(Animal):
def speak(self):
return f"{self.name} barks."
JavaScript:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
}
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"My name is {self.name} and I am {self.age} years o
Forum Donate
person = Person("Alice", 30)
Learn to code — free 3,000-hour curriculum
print(person.greet()) # Output: My name is Alice and I am 30 years
Example:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `My name is ${this.name} and I am ${this.age} years
}
}
Key Differences:
Python Example:
class Bird:
def fly(self):
return "Birds can fly."
class Penguin(Bird):
def fly(self):
return "Penguins cannot fly."
def get_flight_ability(bird):
print(bird.fly())
sparrow = Bird()
penguin = Penguin()
JavaScript Example:
class Bird {
fly() {
return "Birds can fly.";
}
}
class Penguin extends Bird {
Forum Donate
fly() {
Learn to code — free 3,000-hour curriculum
return "Penguins cannot fly.";
}
}
function getFlightAbility(bird) {
console.log(bird.fly());
}
function Calculator() {}
class Calculator {
add(a, b) {
return a + b;
}
multiply(a, b) {
return a * b;
}
}
Python Example:
class Calculator:
def add(self, a, b):
return a + b
calc = Calculator()
print(calc.add(5, 3)) # Output: 8
print(calc.multiply(5, 3)) # Output: 15
Forum Donate
Key Takeaways:
Learn to code — free 3,000-hour curriculum
Python’s OOP model is straightforward, using class ,
__init__ for constructors, and self to refer to instance
attributes.
7. Asynchronous Programming
Asynchronous programming is essential for handling tasks like
network requests, file I/O, or any operation that takes time to
complete.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error:', error);
});
How it works:
import asyncio
import aiohttp
asyncio.run(fetch_data())
How it works:
import aiofiles
import asyncio
asyncio.run(read_file())
Performance Considerations:
Key Takeaways:
JavaScript: Asynchronous programming is central toForum Donate
JavaScript’s design. Its event loop and Promises make it highly
Learn to code — free 3,000-hour curriculum
efficient for real-time, event-driven applications.
// utils.js
module.exports = {
add: (a, b) => a + b,
multiply: (a, b) => a * b,
};
// main.js
const { add, multiply } = require('./utils');
console.log(add(2, 3)); // Output: 5
console.log(multiply(2, 3)); // Output: 6
NPM (JavaScript):
{
"dependencies": {
"express": "^4.18.2"
}
}
pip (Python):
flask==2.3.0
requests==2.31.0
Comparison:
Windows:
myenv\Scripts\activate
macOS/Linux:
source myenv/bin/activate
deactivate
my-node-project/
├── node_modules/ # Installed dependencies
├── src/ # Source code
│ ├── app.js # Entry point
│ ├── utils.js # Utility module
├── package.json # Dependency and project metadata
├── package-lock.json # Dependency tree for consistency
my-python-project/
├── venv/ # Virtual environment
├── src/ # Source code
│ ├── __init__.py # Package initializer
│ ├── app.py # Entry point
│ ├── utils.py # Utility module
├── requirements.txt # Dependency list
Key Takeaways:
1. Modules: Both languages support modular programming.
Python modules are simple .py files, while JavaScript has both
CommonJS and ES6 modules.
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
Forum Donate
else:
print("No errors occurred!")
Learn to code — free 3,000-hour curriculum
finally:
print("Execution complete.")
# Output:
# Error: division by zero
# Execution complete.
try {
const result = 10 / 0;
if (!isFinite(result)) {
throw new Error("Division by zero is not allowed.");
}
} catch (error) {
console.log(`Error: ${error.message}`);
} finally {
console.log("Execution complete.");
}
// Output:
// Error: Division by zero is not allowed.
// Execution complete.
Forum Donate
Debugging in Python:
import logging
logging.basicConfig(level=logging.ERROR)
logging.error("An error occurred.")
Debugging in JavaScript:
Key Takeaways:
Error Handling Syntax: Both Python and JavaScript Forum
use try - Donate
catch constructs, but Python’s except supports catching
Learn to code — free 3,000-hour curriculum
specific exception types.
// Function to test
function add(a, b) {
return a + b;
}
// Mocha test
describe('Add Function', () => {
it('should return the sum of two numbers', () => {
expect(add(2, 3)).to.equal(5);
});
Python: Pytest
Pytest is a widely used framework in Python that emphasizes
simplicity and flexibility. Tests can be written as plain functions, and
Pytest’s built-in fixtures streamline setup and teardown.
Example: Pytest
import pytest
# Function to test
def add(a, b):
return a + b
# Pytest functions
Forum Donate
def test_add_positive_numbers():
Learn to code — free 3,000-hour curriculum
assert add(2, 3) == 5
def test_add_negative_numbers():
assert add(-2, -3) == -5
Key Differences:
"scripts": {
Learn to code — free 3,000-hour curriculum
"test": "mocha",
"coverage": "nyc mocha"
}
This generates a report showing which parts of the code were covered
during tests.
Python: Coverage.py
In Python, coverage.py is the standard tool for measuring test
coverage.
Key Differences:
name: Node.js CI
on: [push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '14'
- run: npm install
- run: npm test
- run: npm run coverage
Python (GitHub Actions): Forum Donate
name: Python CI
on: [push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
python-version: '3.9'
- run: pip install -r requirements.txt
- run: pytest --cov=.
def test_login():
driver = webdriver.Chrome()
driver.get("http://example.com/login")
driver.find_element_by_id("username").send_keys("user")
driver.find_element_by_id("password").send_keys("password")
driver.find_element_by_css_selector("button[type='submit']").cl
assert "dashboard" in driver.current_url
driver.quit()
Key Takeaways:
1. Unit Testing: JavaScript (Mocha/Chai) and Python (Pytest)
frameworks are highly flexible, but Pytest’s concise syntax
makes it particularly beginner-friendly.
import requests
from bs4 import BeautifulSoup
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await browser.close();
})();
Key Differences:
@app.route('/api/data', methods=['GET'])
def get_data():
return jsonify({"message": "Hello, World!"})
if __name__ == '__main__':
app.run(debug=True)
JavaScript: Express
Express is a popular framework for creating REST APIs in JavaScript.
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Key Differences:
import os
import shutil
# Create a directory
os.makedirs("example_dir", exist_ok=True)
# Move a file
shutil.move("source.txt", "example_dir/destination.txt")
const fs = require('fs');
const path = require('path');
// Create a directory
fs.mkdirSync('example_dir', { recursive: true });
// Move a file
fs.renameSync('source.txt', path.join('example_dir', 'destination.t
Forum Donate
// List files in a directory
Learn to code — free 3,000-hour curriculum
fs.readdirSync('example_dir').forEach(file => {
console.log(file);
});
Key Differences:
import pandas as pd
import matplotlib.pyplot as plt
# Create a DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)
const d3 = require('d3');
const data = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
];
svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", (d, i) => i * 100)
.attr("y", d => 300 - d.age * 5)
.attr("width", 50)
.attr("height", d => d.age * 5);
console.log(svg.node().outerHTML);
Key Differences:
import tensorflow as tf
model.compile(optimizer='sgd', loss='mean_squared_error')
# Predict
print(model.predict([5])) # Output: [[10]]
JavaScript: TensorFlow.js
TensorFlow.js brings machine learning capabilities to JavaScript.
const tf = require('@tensorflow/tfjs-node');
Key Differences:
Key Takeaways:
Web Scraping: Python excels with BeautifulSoup for static
content, while Puppeteer is better for dynamic content.
Ecosystem
Learn to code — free 3,000-hour curriculum
Python: PyPI
response = requests.get("https://api.example.com/data")
print(response.json())
JavaScript: NPM
axios.get('https://api.example.com/data')
.then(response => console.log(response.data));
Comparison: Forum Donate
Data Science:
Web Development:
import pandas as pd
import tensorflow as tf
function App() {
return <h1>Hello, World!</h1>;
}
app.listen(3000, () => {
console.log('Server running on port 3000');
});
2. JavaScript:
13. Conclusion
Python and JavaScript are two of the most popular and versatile
programming languages in the world. Each language has its own
strengths, use cases, and ecosystems, making them ideal for different
types of projects.
2. Asynchronous Programming:
3. OOP:
5. Testing:
By adding Python to your skill set, you can become a more versatile
developer, capable of tackling projects that require both web
development expertise and computational power.
3. Online Courses:
4. Practice Platforms:
5. Communities:
Final Thoughts
As a JavaScript developer, you already have a strong foundation in
programming. Python’s clean syntax, extensive libraries, and focus on
readability make it an excellent language to learn next.
The journey to mastering Python will not only broaden your technical
skills but also open doors to exciting domains like data science,
machine learning, and automation, allowing you to tackle diverse
Forum Donate
challenges with confidence.
Learn to code — free 3,000-hour curriculum
German Cocca
I'm a full stack developer (typescript | react | react native | node | express) and
computer science student. In this blog I write about the things I learn along
my path to becoming the best developer I can be.
Our mission: to help people learn to code for free. We accomplish this by creating thousands of
videos, articles, and interactive coding lessons - all freely available to the public.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers,
services, and staff.
Mobile App
Our Charity
About Alumni Network Open Source Shop Support Sponsors Academic Honesty