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
Javascript | Python |
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
Javascript | Python |
var name = “John Doe”; | name = “John Doe” |
var age = 100; | age = 100 |
var isMale = true; | is_male = True |
Utility Methods
Javascript | Python |
“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
Javascript | Python |
var ans = prompt(“What’s up?”); | ans = input(“What’s up?”) |
Arrays vs Lists
Javascript | Python |
var arrStr = [“a”, “b”, “c”]; | lst_str = [“a”, “b”, “c”] |
arrStr[0] | lst_str[0] |
arrStr[-1] // returns undefined | lst_str[-1] # returns “c” |
NA | lst_str[1:] # returns [“b”, “c”] |
NA | lst_str[1:2] # returns [“b”] ignores 3rd |
NA | lst_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”) |
NA | lst_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
Javascript | Python |
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
Javascript | Python |
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
Javascript | Python |
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
Javascript | Python |
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
Javascript | Python |
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
Javascript | Python |
// single line comment | # single line comment |
/*
multi-line comment
can be very long
*/ |
"""
multi-line comment
can be very long
""" |
Imports
Javascript | Python |
// 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
Javascript | Python |
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
Javascript | Python |
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.
Like this:
Like Loading...
Related
[…] article per week on Data Engineering from the perspective of a beginner – the first one was Python for Frontend Engineers. Do not expect a proven pathway to become a Data Engineer someday because I do not have any […]