{JS vs PYTHON Syntax}

Simple Cheet sheet by Shijo Shaji

2

Commenting

3

Printing to Terminal

5

Arithmetic Operators

4

Variables

6

Boolean 

7

Logical Operators

8

If Conditionals

9

While Loops

11

Array/List

10

For Loops

12

Functions

13

Strings

14

Object / Dictionaries

15

TBD

17

TBD

16

TBD

18

TBD

# PRESENTING CODE

Whitespace / Blocks - JS

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")
  }
}

Whitespace is Javascript has no meaning. Blocks of code are declared with braces { }. Indentation is used for readability.

if x == 2:
  print("x must be 2")
else:
  if x == 3:
    print("x must be 3")
  else:
    print("x must be something else")
# PRESENTING CODE

Whitespace / Blocks - Python

You can use space or tab. Without proper indentation, you will get an error

// Single Line Comment
# PRESENTING CODE

Commenting - JS

/*
 * Multiple line:
 *  Anything between here is a
comment- this 
can extend several lines*/
# Single Line Comment
# PRESENTING CODE

Commenting - Python

"""
Multiple Line comment
At this pointanything between triple quotes are comments
"""
// JAVASCRIPT

console.log("print this!")
# PRESENTING CODE

Printing to Terminal 

# PYTHON

print("print this to terminal")
// JS Variables declaration

let x = "Hello there"
const y = "Good bye"
# PRESENTING CODE

Variables

# Python variables declaration

x = "Hello there"
y = "Good bye"

Arithmetic Operators

The arithmetic operators between Javascript and Python are identical — except for one.

Python is missing:

pre-decrement/ post-decrement,

pre-increment/ post-increment operators.

since Python treats all numbers as floats (decimal numbers), you can use the double division sign // to get an integer.

// Javascript users lowercase

let x = true;
let y = false;
# PRESENTING CODE

Boolean

#  Python users Uppercase

x = True;
y = False;
// Javascript

=== Strict equality
!== Strict inequality


// Example:

0 == "0"  // true
0 === "0" // false

0 == []   // true
0 === []  // false

0 == 0    // true
0 === 0   // true
# PRESENTING CODE

Boolean

The boolean operators between Javascript and Python are identical — except for two extra JS operators. Python is missing the strict equality/inequality operators.

// Javascript

!     //Logical inverse, not
&&    //Logical AND
||    //Logical OR
# PRESENTING CODE

Logical Operators

# Python

not    # Logical inverse, not
and    # Logical AND
or     # Logical OR
// 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")
}
# PRESENTING CODE

If Conditionals

# Python

if x == 10:
  print("x is 10")
elif x == 20:
  print("x is 20")
else:
  print("x is something else")
// Javascript

let x = 10
while (x >= 0) {
  console.log(x)
  x--
}
// output: 10 down to 0
# PRESENTING CODE

While Loops

# Python

x = 10
while x >= 0:
  print(x)
  x -= 1
# prints from 10 down to 0
// Javascript

for (let i = 0; i < 10; i++) {
  console.log(i)
}

// Output : 0-9
# PRESENTING CODE

For Loops

# Python

for i in range(10):
  print(i)   
  
# Prints 0-9

# we can iterate over types

a = [10, 20, 30]


for i in a:
  print(i)  # Print 10 20 30

# dictionary
b = {'x':5, 'y':15, 'z':0}


for i in b:
  print(i) # Print x y z (the keys of the dict)
// Javascript Creating Array

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
# PRESENTING CODE

Arrays / Lists - Create

In JS, they are called arrays.

In Python, they are called lists.

#  Python creating List

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
// Javascript Accessing Array

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

a4.length; // 3
# PRESENTING CODE

Arrays / Lists - Access

In JS, they are called arrays.

In Python, they are called lists.

#  Python Accessing List

print(a4[1])  # prints 20

a4[0] = 5;    # change from 10 to 5
a4[20] = 99;  # ERROR: assignment out of range

len(a4)   # 3
// Javascript Add/Remove Array

const fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.push("Kiwi") // adds Kiwi to list 
fruits.pop("Kiwi")  // removes Kiwi from list
# PRESENTING CODE

Arrays / Lists - Add/Remove

In JS, they are called arrays.

In Python, they are called lists.

#  Python Add/Remove List

fruits = ["Banana", "Orange", "Apple", "Mango"]

fruits.append("Kiwi")  # adds Kiwi to list 
fruits.remove("Kiwi")  # removes Kiwi from list
// Javascript Add with index Array

const fruits = ["Banana", "Apple", "Mango"];

fruits.splice(1, 0, "orange")  // will insert the value "orange" as the second element of the fruit
# PRESENTING CODE

Arrays / Lists - Add with index

In JS, they are called arrays.

In Python, they are called lists.

#  Python Add with index List

fruits = ["Banana", "Apple", "Mango"]

fruits.insert(1, "orange")  # will insert the value orange as the second element of the fruit list
// Javascript Add with index Array

const fruits = ["Banana", "Apple", "Mango"];

fruits.pop()
// will remove and return the last element from the list 
# PRESENTING CODE

Arrays / Lists - Remove with index

In JS, they are called arrays.

In Python, they are called lists.

#  Python remove with index List

fruits = ["Banana", "Apple", "Mango", "Grape"]

fruits.pop()
# will remove and return the last element from the list
fruits.pop(2)
# will remove and return the element with index 2 from the list
// Javascript 

const fruits= ["Banana", "Orange", "Lemon", "Apple", "Mango"]
const slicedFruits = letters.slice(1, 3)
console.log(slicedFruits)  // ["Orange", "Lemon"]
# PRESENTING CODE

Arrays / Lists - Slicing

"""
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"]
# PRESENTING CODE

Arrays / Lists - Slicing

"""
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 = ["Banana", "Orange", "Lemon", "Apple", "Mango"]


# For our fruits list, suppose we wanted to slice the first three elements.

print(fruits[:3]) # ["Banana", "Orange", "Lemon"]
print(fruits[-2:]) # ["Apple", "Mango"]

# We can also do all but n last elements of a list:

print(fruits[:-1]) # ["Banana", "Orange", "Lemon", "Apple"]
# PRESENTING CODE

Arrays / Lists - Sorting

// Javascript

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.
    .sorted() generates a new list instead of modifying one that already exists and sorts
""" 

names = ["Xander", "Buffy", "Angel", "Willow", "Giles"]
names.sort()
print(names)  # ['Angel', 'Buffy', 'Giles', 'Willow', 'Xander']

# Reverse List and sort
names.sort(reverse=True)
print(names) # ['Xander', 'Willow', 'Giles', 'Buffy', 'Angel']


# sorted()
sorted_names = sorted(names)
print(sorted_names) # ['Angel', 'Buffy', 'Giles', 'Willow', 'Xander']
// Javascript

function foobar(x, y, z) {
  console.log(x, y, z)
  return 12
}

// Arrow Function

let hello = () => {
  console.log("hello")
  console.log("world")
}
// prints hello, then world
# PRESENTING CODE

Function

# Python

def foobar(x, y, z):
  print(x, y, z)
  return 12

// Javascript .toUpperCase() / toLowerCase()

let str = "Hello World!"
str.toUpperCase() // HELLO WORLD!

str.toLowerCase() // hello world!
# PRESENTING CODE

String

# Python .upper() / .lower()

str = "Hello World!"
str.upper() # HELLO WORLD!

str.lower() # hello world!

Strings in Python and Javascript both use single and double-quotes

// Javascript 

let food1 = {}                 // empty object
let food2 = {pizza: "tomato"}  // property quotes optional
// common multiline format
let prices= {  
  "pizza": 20,
  "pasta": 1.2,
  "drink": "free"
}

console.log(prices.pizza)      // prints 20
console.log(prices["drink"])   // prints free
# PRESENTING CODE

Object / Dictionaries

# Python 

food1 = {}                   # empty dict
food2 = {"pizza": "tomato"}  # key quotes are required
# multiline format
prices = {  
  "pizza": 20,
  "pasta": 1.2,
  "drink": "free"
}

print(prices["pizza"])  # Prints 20

In Javascript, objects hold data that can be found using a key called a property.

In Python, these key/value pairs are called dictionaries.

Get in touch

Made with Slides.com