Javascript vs Python Syntax Cheatsheet
I was looking for a quick way to learn Python after I’ve learned Ruby and Javascript. I needed a quick cheat sheet with some syntax differences and high-level concept differences of the two languages.
Often, when I would come across Python code online, I would be able to make out the logic — like I’m sure most programmers would after learning Javascript. Writing code in python? That’s a different story.
This cheat sheet serves as high-level comparisons between the two languages to get you started on the track to learning Python after Javascript or just wanting to improve your understanding of Python code on online documentation. Bookmark this page to keep it handy! Happy programming.
Note: This is written with the latest version of Python at the time of writing- Python 3.
Whitespace / Blocks
Javascript
Whitespace is Javascript has no meaning. Blocks of code are declared with braces { }. Indentation is used for readability.
if (x == 2) {
console.log("x must be 2")
} else {
if (x == 3) {
console.log("x must be 3")
} else {
console.log("x must be something else")
}
}
Python
In Python, the amount of whitespace tells the computer what is part of a function and what is not part of that function. You can use space or tab. Without proper indentation, you will get an error.
if x == 2:
print("x must be 2")
else:
if x == 3:
print("x must be 3")
else:
print("x must be something else")
Commenting
Javascript
Single line:
// Text after two forward slashes is a comment
Multi-line:
/* Anything between here is a
comment- this
can extend several lines*/
Python
Single line:
# Anything after a # is a comment
Multi-line:
Python doesn't have multi-line comments, but you can use its multi-line string option.
"""
At this point we wish
to print out some numbers
and see where that gets us
"""
Printing to Terminal
Javascript
console.log("print this!")
Python
print("print this!")
Variables
Javascript
Javascript has several ways to declare a variable using “let” or “const”, depending on whether the variable needs to be updated in the future (“var” can also be used, but it’s an outdated way of declaring variables).
let x = "Hello there"
const y = "Good bye"
Python
x = "Hello there"
y = "Good bye"
Arithmetic Operators
The arithmetic operators between Javascript and Python are identical — except for one. Python is missing the pre-decrement/ post-decrement, and pre-increment/ post-increment operators.
Javascript extra operators:
-- Pre-decrement, post-decrement
++ Pre-increment, post-increment
Python extra operator:
One thing to note- since Python treats all numbers as floats (decimal numbers), you can use the double division sign // to get an integer. This is useful for finding indexes.
string1 = "abcde" middle = string1[len(string1) // 2]
print(middle) # c
Literal Boolean Values
Javascript
JS literal booleans use the lowercase version.
x = true
y = false
Python
PY literal booleans use the uppercase version.
x = True
y = False
Boolean Operators
The boolean operators between Javascript and Python are identical — except for two extra JS operators. Python is missing the strict equality/inequality operators.
Javascript extra operators:
=== Strict equality
!== Strict inequality
Example of strict equality/inequality:
0 == "0" // true
0 === "0" // false
0 == [] // true
0 === [] // false
0 == 0 // true
0 === 0 // true
With Python, since we don’t have strict equality/inequality operators, this means we would need to convert the data to the same type before making comparisons.
Logical Operators
Javascript
! Logical inverse, not
&& Logical AND
|| Logical OR
Python
Python’s logical operators are read friendly
not Logical inverse, not
and Logical AND
or Logical OR
If Conditionals
Most notable difference: Python uses “elif” instead of “else if”.
Javascript
if (x == 10) {
console.log("x is 10")
} else if (x == 20) {
console.log("x is 20")
} else {
console.log("x is something else")
}
Python
if x == 10:
print("x is 10")
elif x == 20:
print("x is 20")
else:
print("x is something else")
Arrays / Lists
- In JS, they are called arrays. In Python, they are called lists.
- Python: 2D Lists: heights = [ [“Noelle”, 61], [“Ava”, 70], [“Sam”, 67], [“Mia”, 64] ]
Javascript
Creating:
let a1 = new Array() // Empty array
let a2 = new Array(10) // Array of 10 elements
let a3 = [] // Empty array
let a4 = [10, 20, 30] // Array of 3 elements
let a5 = [1, 2, "b"] // No problem
Accessing:
console.log(a4[1]) // prints 20
a4[0] = 5 // change from 10 to 5
a4[20] = 99 // OK, makes a new element at index 20
Length/Number of elements:
a4.length; // 3
Adding/removing items
fruits.push("Kiwi") // adds Kiwi to list
fruits.pop("Kiwi") // removes Kiwi from list
Python
Creating:
a1 = list() # Empty list
a2 = list((88, 99)) # List of two elements
a3 = [] # Empty list
a4 = [10, 20, 30] # List of 3 elements
a5 = [1, 2, "b"] # No problem
Accessing:
print(a4[1]) # prints 20
a4[0] = 5; # change from 10 to 5
a4[20] = 99; # ERROR: assignment out of range
Length/Number of elements:
len(a4) # 3
Adding/removing items
fruits.append("Kiwi") # adds Kiwi to list
fruits.remove("Kiwi") # removes Kiwi from list
Bonus: How to remove from a 2D list
customer_data = [["Ainsley", "Small", True],["Ben", "Large", False]]
customer_data[1].remove("Ben")# removes "Ben" from second array
# [["Ainsley", "Small", True],["Large", False]]
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, 3)
print(x[1]) # prints 2y = (10,)
# A tuple of one element, comma required
List Methods
Additional ways of working with lists
Insert:
A list method to insert an element from a specific index of a list
Javascript .splice()
fruits.splice(1, 0, "orange")// will insert the value "orange" as the second element of the fruit list (deleting 0 items first)
Python .insert()
fruits.insert(1, "orange")# will insert the value "orange" as the second element of the fruit list
Pop:
A list method to remove an element from a specific index or end of the list.
Javascript .pop()
In Javascript, this method can only be used to remove the last element on the list.
fruits.pop()// will remove and return the last element from the list
Python .pop()
In Phython, this method can be used to remove an element from specific index, or the last element on the list.
fruits.pop()
# will remove and return the last element from the listfruits.pop(2)
# will remove and return the element with index 2 from the list
Slicing:
A list method to extract only a portion of the list.
Javascript .slice()
const fruits= ["Banana", "Orange", "Lemon", "Apple", "Mango"]const slicedFruits = letters.slice(1, 3)
console.log(slicedFruits)// ["Orange", "Lemon"]
Python [start : end]
In Python, we perform slicing using the following syntax: [start: end]. start
is the index of the first element that we want to include in our selection.end
is the index of one more than the last index that we want to include.
fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]sliced_fruits = fruits[1:3]
print(sliced_fruits)# ["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:]
For our fruits
list, suppose we wanted to slice the first three elements.
fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]print(fruits[:3])
# ["Banana", "Orange", "Lemon"]print(fruits[-2:])
# ["Apple", "Mango"]
We can also do all but n last elements of a list:
fruits[-n:]print(fruits[:-1])
# ["Banana", "Orange", "Lemon", "Apple"]
Sorting:
A method and a built-in function to sort a list. Both Javascript and Python have the .sort()
method that will sort either alphabetically or numerically.
Javascript .sort()
Note: If numbers are sorted as strings, “25” is bigger than “100”, because “2” is bigger than “1”.
const names = ["Xander", "Buffy", "Angel", "Willow", "Giles"]names.sort()
console.log(names)// ['Angel', 'Buffy', 'Giles', 'Willow', 'Xander']
Python .sort() / .sorted()
.sort() Sort modifies the list directly.
names = ["Xander", "Buffy", "Angel", "Willow", "Giles"]names.sort()
print(names)# ['Angel', 'Buffy', 'Giles', 'Willow', 'Xander']
.sort()
also provides us the option to go in reverse easily. Instead of sorting in ascending order, we can do so in descending order.
names = ["Xander", "Buffy", "Angel", "Willow", "Giles"]names.sort(reverse=True)
print(names)# ['Xander', 'Willow', 'Giles', 'Buffy', 'Angel']
.sorted() is different from .sort()
because it comes before a list, instead of after. And, It generates a new list instead of modifying one that already exists.
names = ["Xander", "Buffy", "Angel", "Willow", "Giles"]sorted_names = sorted(names)
print(sorted_names)# ['Angel', 'Buffy', 'Giles', 'Willow', 'Xander']
Bonus for Python:
.range()
A built-in python function to create a sequence of integers. The function range()
takes a single input, and generates numbers starting at 0
and ending at the number before the input.
my_range = range(10)
print(my_range)
# range(0, 10)
This creates a range object. If we want to use this object as a list, we need to convert it using a built-in function called list()
.
print(list(my_range))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
We can also call range()
with two inputs, and create a list that starts at a different number.
my_list = range(2, 9)
print(list(my_list))
# [2, 3, 4, 5, 6, 7, 8]
We can also call range()
with three inputs, and create a list that “skips” numbers. For example, we’ll start at 1
and skip in increments of 10
between each number until we get to 100
:
my_range3 = range(1, 100, 10)
print(list(my_range3))
# [1, 11, 21, 31, 41, 51, 61, 71, 81, 91]
.count()
Unlike Javascript, Python has a built-in way to count occurrences of an item in a list without having to write a function for it.
letters = ["m", "i", "s", "s", "i", "s", "s", "i", "p", "p", "i"]num_i = letters.count("i")
print(num_i)# 4
This method even works to count element appearances in a 2D list.
number_collection = [[100, 200], [100, 200], [475, 29], [34, 34]]num_pairs = number_collection.count([100, 200])
print(num_pairs)# 2
For Loops
Iteration.
Javascript
for (let i = 0; i < 10; i++) {
console.log(i)
}
Python
We can use the range()
function to count:
for i in range(10):
print(i) # Prints 0-9
Or, we can iterate over types:
a = [10, 20, 30]
# Print 10 20 30
for i in a:
print(i)
# A dictionary
b = {'x':5, 'y':15, 'z':0}
# Print x y z (the keys of the dict)
for i in b:
print(i)
While Loops
While the condition is true.
Javascript
let x = 10
while (x >= 0) {
console.log(x)
x--
}// prints 10 down to 0
Python
x = 10
while x >= 0:
print(x)
x -= 1# prints from 10 down to 0
Functions
Defining functions.
Javascript
function foobar(x, y, z) {
console.log(x, y, z)
return 12
}
Arrow functions
let hello = () => {
console.log("hello")
console.log("world")
}// prints hello, then world
Python
def foobar(x, y, z):
print(x, y, z)
return 12
Strings
Strings in Python and Javascript both use single and double-quotes. String methods do differ between the two. Here are a few examples:
Javascript .toUpperCase() / toLowerCase()
.toUpperCase()
returns the string with all uppercase characters.
let str = "Hello World!"
str.toUpperCase()// HELLO WORLD!
.toLowerCase()
returns the string with all lowercase characters.
let str = "Hello World!"
str.toLowerCase()// hello world!
Python .upper() / .lower()
.upper()
returns the string with all uppercase characters.
str = "Hello World!"
str.upper()# HELLO WORLD!
.lower()
returns the string with all lowercase characters.
str = "Hello World!"
str.lower()# hello world!
You can see a list of available Python string methods here.
Object / Dictionaries
In Javascript, objects hold data that can be found using a key called a property. In Python, these key/value pairs are called dictionaries.
Javascript
let food1 = {} // empty object
let food2 = {pizza: "tomato"} // property quotes optional// common multiline format
let prices= {
"pizza": 20,
"pasta": 1.2,
"drink": "free"
}
Access:
console.log(prices.pizza) // prints 20
console.log(prices["drink"]) // prints free
Python
food1 = {} # empty dict
food2 = {"pizza": "tomato"} # key quotes are required# multiline format
prices = {
"pizza": 20,
"pasta": 1.2,
"drink": "free"
}
Access:
print(prices["pizza"]) # Prints 20
Classes
A class is a template for a data type. Both Javascript & Python uses theclass
keyword with a capitalization convention.
Javascript
Modern JS introduced the class
keyword and a syntax more familiar to most other OOP languages. Note that the inheritance model is still prototypal inheritance.
class Creature {
constructor(type) {
this.type = type
}
}
Access:
class Goat extends Creature {
constructor(name) {
super("mammal")
this.legs = 4
this.name = name
}
goat = new Goat("billy")
goat.type // "mammal"
goat.name // "billy"
goat.jump() // "I'm jumping! Yay!"
Python
Python has a class constructor method that is called “dunder” (ex: __init__()
). This stands for double underscores.
class Shouter:
def __init__(self):
print("HELLO?!")class Creature:
def __init__(self, type): # constructor
self.type = type
Access:
You can access all of an object’s class variables with object.variable
syntax.
class Musician:
title = "Rockstar"
drummer = Musician()
print(drummer.title)# prints "Rockstar"
Note: There’s another dunder method called __repr__()
. This is a method we can use to tell Python what we want the string representation of the class to be.
class Employee():
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
argus = Employee("Argus Filch")
print(argus)# without using __repr__()
# printed "<__main__.Employee object at 0x104e88390>"# after using __repr__()
# prints "Argus Filch"