Python for Frontend Engineers


Py thee on.

— William Shakespeare (meaning Python code turns you on) ๐Ÿ˜…

I tried to teach Python to myself for a week and now I’m able to read and understand Python code comfortably. This blog summarises my thought process while learning Python and comparing its syntax with Javascript at every step. I’ll keep updating it as and when I encounter new Pythonic stuff.

First and foremost, wear a gauntlet and snap a finger for semicolons, curly braces, and camelCase names to bite the dust.

console.log vs print

JavascriptPython
console.log(“Hello World!”);print(“Hello World!”)
console.log(“Hello ” + “World!”);print(“Hello ” + “World!”)
var greet = “Hello”;
var who = “World!”;
console.log(`${greet} ${who}`);
greet = “Hello”
who = “World!”
print(“{0} {1}”.format(greet, who))

Primitive Types

JavascriptPython
var name = “John Doe”;name = “John Doe”
var age = 100;age = 100
var isMale = true;is_male = True

Utility Methods

JavascriptPython
“amit”.toUppercase(); “amit”.upper() # “amit”.upper().isupper()
“amit”.length;len(“amit”)
“amit”.indexOf(“a”);“amit”.index(“a”) // throws error if not found ๐Ÿ˜ฆ
String(100);str(100)
parseInt(100.300, 10);int(100.300)
parseFloat(100.300, 10);float(100.300)
Math.abs(-100);abs(-100)
Math.pow(3, 2);pow(3, 2)
Math.round(3.2);round(3.2)
Math.floor(3.2);floor(3.2)
Math.ceil(3.2);ceil(3.2)
Math.sqrt(25);sqrt(25)
NA (use Lodash)max(4, 2)
NA (use Lodash)min(4, 2)

User Input

JavascriptPython
var ans = prompt(“What’s up?”);ans = input(“What’s up?”)

Arrays vs Lists

JavascriptPython
var arrStr = [“a”, “b”, “c”];lst_str = [“a”, “b”, “c”]
arrStr[0]lst_str[0]
arrStr[-1] // returns undefinedlst_str[-1] # returns “c”
NAlst_str[1:] # returns [“b”, “c”]
NAlst_str[1:2] # returns [“b”] ignores 3rd
NAlst_str[:2] # returns [“a”, “b”] ignores 3rd
arrStr[1] = “d”;lst_str[1] = “d”
arrStr.push(“d”); lst_str.append(“d”)
arrStr.splice(1, 0, “f”);lst_str.insert(1, “f”)
arrStr.indexOf(“b”);lst_str.index(“b”)
NAlst_str.count(“d”) # returns 2 occurrences
arrStr = arrStr.sort();lst_str.sort()
arrStr.reverse();lst_str.reverse()
var arrNum = [1, 2, 3];lst_num = [1, 2, 3]
arrStr = arrStr.concat(arrNum);lst_str.extend(lst_num)
var arrStr2 = arrStr.slice();lst_str2 = lst_str.copy()

Tuple in Typescript vs Tuple in Python

JavascriptPython
var point = [“x”, “y”];point = (“x”, “y”)
point[1];point[1]
var arrTuple = [[“x”, “y”], [“w”, “z”]];list_tuple = [(“x”, “y”), (“w”, “z”)]

function vs def

JavascriptPython
function greetMe(name){
    console.log(
       "Hi! " + name
    );
}
def greet_me(name):
    print("Hi! " + name)
 
 
 


function greetMe(name){
    return "Hi! " + name;
}
def greet_me(name):
    return "Hi! " + name

 

If Statements

JavascriptPython
if ((1&&1)||(2 === 2)) {
  console.log("124");
} else if (1 !== 2) {
  console.log("421");
} else {
  console.log("Lakhan!");
}
if (1 and 1) or (2 == 2):
   print("124")
elif (1 != 2):
   print("421")
else:
  print("Lakhan!")
 

Objects vs Dictionaries

JavascriptPython
var objRomans = {
  "five": "V",
  "ten":"X"
}
dict_romans = {
  "five": "V",
  "ten":"X"
}
// Returns undefined
// if key not exists
objRomans["five"]
# throws an error
# if key not exists
dict_romans["five"]

Loops

JavascriptPython
var i = 0;
var crossedLimit = false;
while (i !== 10) {
  i += 1;
  crossedLimit = i==10;
  if (!crossedLimit) {
    console.log(i);
  }
}
i = 0
crossed_limit=False
while i != 10:
  i += 1
  crossed_limit = i == 10
  if not(crossed_limit):
    print(i)
 
 
var name = "Amit";
var l = name.length;
for (var i = 0;i<l;i++) {
  console.log(
    name.charAt(i)
  );
}
name = "Amit"
 
for char in name:
  print(char)
 
 
 
var names = ["A", "M"];
for (let name in names) {
  console.log(
    names[name]
  );
}
names = ["A", "M"]
for name in names:
  print(name)
 
 

Comments

JavascriptPython
// single line comment
# single line comment
/*
  multi-line comment
  can be very long
*/
"""
  multi-line comment
  can be very long
"""

Imports

JavascriptPython
// imports everything
// from cookies.js
import "./cookies";

// imports `a`
// from cookies.js
import a from "./cookies";
# imports everything
# from cookies.py
import cookies

# imports `a`
# from cookies.py
from cookies import a

Try Catch vs Try Except

JavascriptPython
try {
  let obj = JSON.parse("")
} catch(e) {
  console.log(e.message);
}
import json
try:
  dict = json.loads("")
except Exception as e:
  print(str(e))

Classes

JavascriptPython
class Bike {
  isBikeToo() {
    return true;
  }
}

class Car
extends Bike {
  constructor(
    tire
  ) {
    super();
    this.tire=tire;
  }

  whoAmI() {
    if(this.tire==3){
      return "Auto";
    } else {
      return "Bike";
    }
  }
}

var c=new Car(3);
console.log(
  c.tire,
  c.whoAmI(),
  c.isBikeToo()
);
class Bike:
  def is_bike_too(self):
    return True
 
 

class Car(Bike):
   
  def __init__(self, tire):
     
    
    
    self.tire = tire


  def who_am_i(self):
    if self.tire == 3:
      return "Auto"
    else:
      return "Bike"
 
 
 
 
c = Car(3)
print("{0} {1} {2}".format(
  str(c.tire),
  c.who_am_i(),
  str(c.is_bike_too())
))
If you found this article useful in anyway, feel free to donate me and receive my dilettante painting as a token of appreciation for your donation.

One thought on “Python for Frontend Engineers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.