Références:
- Programming language syntax comparison
- W3School Javascript Tutorial
- W3School Python Tutorial
- Python3 VS ES6 syntax comparison
- Javascript vs Python Syntax Cheatsheet
- Python VS JavaScript – What are the Key Differences
Overview
Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation.
Python is dynamically-typed and garbage-collected. It supports multiple programming paradigms, including structured (particularly procedural), object-oriented and functional programming. It is often described as a “batteries included” language due to its comprehensive standard library.
JavaScript is a high-level, often just-in-time compiled language that conforms to the ECMAScript standard.
It has dynamic typing, prototype-based object-orientation, and first-class functions. It is multi-paradigm, supporting event-driven, functional, and imperative programming styles. It has application programming interfaces (APIs) for working with text, dates, regular expressions, standard data structures, and the Document Object Model (DOM).
History
Syntax
"""
A multiline comment
Also useful to comment out several lines of codes
"""
# Variables
a = 2
# Multiple time same assignment
a = b = c = 3;
# Multiple assigments on one line thanks to destructuring
x, y = 5, 11
# Constant are usually written in capital letters,
# but nothing prevents a future re-assignment in Python
PI = 3.14
# Function definition
def add_numbers(a, b):
return a + b
# Function calling
add_numbers(1, 2)
add_numbers(a=1, b=2)
# Lambda (anonymous) function
add_numbers = lambda a, b: a + b
/* A multiline comment
Also useful to comment out several lines of codes
*/
/* There are multiple ways to declare variables */
a = 2; // Avoid it. Is the same as window.a = 2
var b = 3 // Avoid it and use let
let c = 4;
const d = 5;
// A normal function definition
function helloWorld() {
console.log("Hello world!";
}
helloWorld(); // () calls the function
// An anonymous function
let add = function(x, y) {
return x+ y;
}
// Arrow functions
let add3 = (x, y) => { return x + y }
let add4 = (x, y) => x + y
Hello world!
print("Hello world!") # "Hello World\n"
console.log("Hello world!");
Comments
# Single line comment
"""
multi-line
comments
"""
// Single line comment
/*
multi-line
comments
*/
Naming conventions
Python recommends (PEP8):
snake_case
for variables and functionsPascalCase
for classesSNAKE_CASE
(screaming snake case) for constants
JavaScript style guides usually recommends:
camelCase
for variables and functionsPascalCase
for classes, interfaces and namespacesSNAKE_CASE
(screaming snake case) for constants
Basic types
a_bool = True # Uppercase literal
a_number = 123
a_string = "abc"
a_list = [1, 2, 3]
a_tuple = (1, 2, 3) # Parenthesis are not strictly required, it's the comma that makes the tuple
a_set = {1, 2, 3}
a_dict = {"a": 1, "b": 2, "c": 3} # Access keys with indexers: a_dict["a"]
an_object = SomeClass() # Access keys with dot-access: an_object.a
const aBool = true; // Lowercase literal
const aNumber = 123;
const aString = 'abc';
const anArray = [1, 2, 3];
// Arrays are used as tuples in Javascript
const aSet = new Set([1, 2, 3]);
// Javascript does not differentiate between a dictionary and an object
const anObject = {a: 1, b: 2, c: 3}; // Access keys with dot-access: anObject.a
Numeric data types
>>> type (100)
<class 'int'>
>>> type (100.2)
<class 'float'>
The int() function converts a string or float to int.
>>> int('100')
100
>>> int('-10')
-10
>>> int('5.5')
5
To go beyond the restriction of 32-bit or 64-bit arithmetic, you can install mpmath
, Python library for arbitrary-precision floating-point arithmetic.
let number = 100;
let anotherNumber = 100.2;
let bigInt = 1234567890123456789012345678901234567890n; // ends with n
let sameBigInt = BigInt("1234567890123456789012345678901234567890");
The parseInt() function converts a string to int.
parseInt('5.5') // Output: 5
Tuples
Python supports a read-only type of list called a tuple. It’s immutable — you can’t change or modify it.
>>> x = (1, 2, "some text")
>>> print(x[1])
2
y = (10,) # A tuple of one element, comma required
List / arrays
# Creating
a1 = list() # Empty list
a2 = list((1, 2)) # List of two elements
a3 = [] # Empty list
a4 = [1, 2, 3] # List of 3 elements
a5 = [1, 2, "b"] # Any data type is possible
# Accessing
a4[1] # Output: 2
a4[0] = 5; # Change from 1 to 5
a4[20] = 99; # ERROR: assignment out of range
# Length
len(a4) # Output: 3
# Adding
fruits = ["Apple", "Banana"]
fruits.append("Kiwi") # Adds Kiwi to list
# Removing
fruits.remove("Kiwi") # Removes Kiwi from list
fruit1 = fruits.pop() # Removes last element from the list and returns it
fruit2 = fruits.pop(1) # Removes second element from the list and returns it
# Inserting
fruits.insert(1, "Orange") # Insert the value "Orange" as the second element of the fruit list
# Slicing
fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]
fruits[1:3] # ["Orange", "Lemon"]
# Slicing in Python is very flexible. If we want to select the first n elements of a list
# or the last n elements in a list, we could use the following code:
# fruits[:n]
# fruits[-n:]
fruits[:3] # ["Banana", "Orange", "Lemon"]
fruits[-2:] # ["Apple", "Mango"]
# We can also do all but n last elements of a list:
# fruits[:-n]
fruits[:-1] # ["Banana", "Orange", "Lemon", "Apple"]
# Sorting
fruits.sort() # Sort the list
fruits.sort(reverse=True) # Same in reverse order
sorted_fruits=sorted(fruits) # Return a new sorted list
# Counting
fruits.count("Orange") # 1
// Creating
let a1 = new Array(); // Empty array
let a2 = new Array(10); // Array of 10 elements
let a3 = []; // Empty array
let a4 = [1, 2, 3]; // Array of 3 elements
let a5 = [1, 2, "b"]; // Any data type is possible
// Accessing
a4[1]; // Output: 2
a4[0] = 5; // Change from 10 to 5
a4[20] = 99; // OK, makes a new element at index 20
// Length
a4.length; // Output: 3
// Adding
fruits = ["Apple", "Banana"];
fruits.push("Kiwi"); // Adds Kiwi to list
// Removing
fruits.pop("Kiwi"); // Removes Kiwi from list
fruit = fruits.pop(); // Removes last element from the list and returns it
// Inserting
fruits.splice(1, 0, "Orange"); // Will insert the value "Orange" as the second element of the fruit list (deleting 0 items first)
// Slicing
const fruits= ["Banana", "Orange", "Lemon", "Apple", "Mango"];
fruits.slice(1, 3); // Output: ["Orange", "Lemon"]
// Sorting
fruits.sort() // Sort the list
Dictionnaries / objects
Python dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered (since Python 3.7), changeable and do not allow duplicates.
# Empty dict
d = {}
# Creating a dict, two possibilies
user = { "name": "Hervé", "age": 46, "country": "France" } # Mandatory quotes around keys
user_alt = dict(name = "Hervé", age = 46, country = "France")
user == user_alt # Output: True
# Lenght
len(user) # Output: 3
# Adding key
user["admin"] = True
user == user_alt # Output: False
# Accessing key
user["name"] # Output: Hervé
# Testing if key exists
"name" in user # Output: True
# Accessing keys and items
user.keys() # Output: dict_keys(['name', 'age', 'country', 'admin'])
user.values() # Output: dict_values(['Hervé', 46, 'France', True])
user.items() # Output: dict_items([('name', 'Hervé'), ('age', 46), ('country', 'France'), ('admin', True)])
# Looping through key, value
for k, v in user.items(): print(k, ':', v)
# Output:
# name : Hervé
# age : 46
# country : France
# admin : True
# Deleting key
del user["country"]
// Empty object
let o1 = {};
let o2 = new Object(); // Same as above
let o3 = Object.create(null); // Removes all the methods inherited from Object.prototype
// Initializing properties
let user = { name: "Hervé", age: 46, country: "France" }; // Property quotes optional
// Common multiline format
let user_alt = {
"name": "Hervé",
"age": 46,
"country": "France"
}
// Accessing key
user["name"] // Output: Hervé
// Also with dotted notation
user.name // Output: Hervé
// Testing if key exists
"name" in user // Output: true
// Adding key
user["admin"] = true;
// In Javascript, we can add method to objects
user.birthYear = function() {
const date = new Date();
return date.getFullYear() - this.age;
}
user.birthYear() // Output: 1976
// Accessing keys, values and entries (i.e. array of key, values)
Object.keys(user) // Output: Array(3) [ "name", "age", "country" ]
Object.values(user) // Output: Array(3) [ "Hervé", 46, "France" ]
Object.entiers(user) // Output : Array(3) [ (2) […], (2) […], (2) […] ]
// Looping over keys, values and entries
for (const key of Object.keys(user)) { console.log(key + ":" + user[key]) }
for (const value of Object.values(dict)) { console.log(value) }
for (const [key, value] of Object.entries(dict)) { console.log(key + ":" + value) }
// Deleting key
delete user["country"]
Arithmetic operators
OPERATOR | PYTHON | JAVASCRIPT |
---|---|---|
addition | + | + |
subtraction | - | - |
multiplication | * | * |
exponent | ** | ** |
division | / | / |
floor division | // | n/a |
modulo | % | % |
Comparison operators
OPERATOR | PYTHON | JAVASCRIPT |
---|---|---|
greater than | > | > |
less than | < | < |
greater or equal than | >= | >= |
less or equal than | <= | <= |
equal | == | == |
strict (triple) equal | n/a | === |
not equal | != | != |
strict not equal | n/a | !== |
Python is predictable when comparing values:
9 == "9" # Output: False
JavaScript on the other hand performs a conversion every time the abstract comparison operator is involved. To avoid the conversion you must use the “strict comparison operator”, also called triple-equal:
9 == "9" // Output: true
9 === "9" // Output: false
Logical operators
OPERATOR | PYTHON | JAVASCRIPT |
---|---|---|
logical and | and | && |
logical or | or | |
logical negation | not | ! |
String interpolation
Python
With f-strings
a = 2
f"My {a} cents"
JavaScript
With a template literal using back ticks ``
const a = 2;
`My ${a} cents`
Looping
Python
This is why I ❤️ Python: so clear and concise.
languages = ['Python', 'Javascript', 'PHP', 'Ruby', 'Basic']
for language in languages:
print(language)
JavaScript
OMG 😱 … so many possibilities!
const languages = ['Python', 'Javascript', 'PHP', 'Ruby', 'Basic']
// Traditional C-like
for (let i = 0; i < languages.length; i++) {
console.log(languages[i]);
}
// ES5 forEach
languages.forEach(function (item, index) {
console.log(item);
});
// ES6 forEach with arrow function
languages.forEach(item => console.log(item));
// ES6 for-of
for (language of languages) {
console.log(language);
}
Conditionals (If-then-else)
if condition:
# Code
elif condition2:
# Code
else:
# Code
# ternary operator:
true_val if condition else false_val
if (condition) {
// Code
} else if (condition2) {
// Code
} else {
// Code
}
// ternary operator:
condition ? trueVal : falseVal;
Lambdas (anonymous functions)
lambda a: a * 2
a => a * 2
Slices
arr_slice = arr[start:end]
str_slice = str[start:end]
const arrSlice = arr.slice(start, end)
const strSlice = str.substring(start, end)
Destructuring (or unpacking)
a, b, c = [1, 2, 3]
print(a,b,c)
# 1 2 3
a, *mid, b = [1, 2, 3, 4, 5, 6]
print(a, mid, b)
# 1 [2, 3, 4, 5] 6
status, data = getResult()
See MDM
let a, b, rest;
[a, b] = [1, 2];
console.log(a, b);
// 1 2
[a, b, ...rest] = [1, 2, 3, 4, 5];
console.log(rest);
// [3, 4, 5]
let [status, data] = getResult();
Spread
search(**parameters)
searchDb(...parameters);
Enumerate
values = ['A', 'B', 'C'];
for count, value in enumerate(values):
print(count, value)
const array = ['A', 'B', 'C'];
for (const [count, value] of array.entries()) {
console.log(count, value);
}
To be continued
Python
JavaScript