DEV Community

Cover image for Learn Python as a Javascript developer
Kachi Cheong
Kachi Cheong

Posted on

Learn Python as a Javascript developer

As a coder, you should always be looking to expand your knowledge. The best way to do this is by learning different coding languages and frameworks.

I myself am a Javascript and Python fullstack developer and like most self-taught developers, I started by learning HTML, CSS and Javascript first.

Eventually I learned Python and found it very useful. Python is great for handling backend data and creating simple scripts like web-scrapers.

If you're nervous about learning Python, remember that Python is a high level programming language. This means it is around the same level of difficulty to learn as Javascript.

I would even argue it is easier to learn than javascript, and the transition from Javascript to python much smoother than the other way round.

In this tutorial, I'll outline the main differences between the two coding languages.

Set Up

Firstly, make sure Python is installed on your machine before you start.

You can check this by running this command in your terminal:

python3 --version
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can use a sandbox to test Python code.

Methods

The methods used in python and javascript are named differently.

Here are some examples of this:

In javascript:

"Hello World".length; // Length of a string
arr.push("new string"); // Add new item to end of array
arr.sort((a, b) => a - b); // Sort an array
Enter fullscreen mode Exit fullscreen mode

In python:

len("Hello world") # Length of a string
arr.append("new string") # Add new item to end of list
arr.sort() # Sort a list
Enter fullscreen mode Exit fullscreen mode

As you can see, the differences aren't huge and you of course don't need to remember all of them.

Here are some useful links for you to reference:

Type Page
Strings Methods
List/Array Methods
Functions Keywords

Output

When you want to log something in the terminal or browser. Just change console.log to print!

In javascript:

console.log("hello world");
Enter fullscreen mode Exit fullscreen mode

In python:

print("hello world")
Enter fullscreen mode Exit fullscreen mode

Comments

When leaving a comment or commenting something out change // to #:

In javascript:

// javascript comment

/* multiline
javascript
comment */
Enter fullscreen mode Exit fullscreen mode

In python:

"""Python comment"""

# Multi
# Line
# Comment
Enter fullscreen mode Exit fullscreen mode

Variables

There are a couple difference between Javascript and Python variables.

  • Javascript use camel casing and Python use snake casing.
  • const, let and var for javascript. Cases for python.

In Javascript:

var myExample = "hello world"; // global variable
let myExample = "hello world"; // scope variable
const myExample = "hello world"; // unchangeable variable (scope)
Enter fullscreen mode Exit fullscreen mode

In Python:

my_example = "hello world" # basic variable
MY_EXAMPLE = "hello world" # Red flag to not change
Enter fullscreen mode Exit fullscreen mode

Note: In python, every variable is mutable. There is no real way to prevent this. When writing code in python, changing the case of the variable can signal to other programmers that the variable should not be changed.

List and Arrays

There are a few differences between Javascript and Python arrays.

  • What we refer to as arrays in Javascript are called lists in Python.
  • Javascript use camel casing and Python use underscores.
  • const, let and var are used in javascript. Cases are used in python.

In Javascript:

const myList = [4, 5, 6];
Enter fullscreen mode Exit fullscreen mode

In Python:

my_list = [1, 3, 5]
Enter fullscreen mode Exit fullscreen mode

Functions

Javascript uses curly braces {} and function (or an arrow function):

function foo(str) {
  console.log(str);
}

const foo = (str) => console.log(str);
Enter fullscreen mode Exit fullscreen mode

Python uses def followed by a colon : for their functions:

def foo(str):
    print(str)
Enter fullscreen mode Exit fullscreen mode

If Statements

Javascript uses curly braces {} and parenthesis () for each condition separated by a else if or else:

if (condition1) {
  console.log("condition 1 met");
} else if (condition2) {
  console.log("condition 2 met");
} else {
  console.log("else condition");
}
Enter fullscreen mode Exit fullscreen mode

Python just uses colons : after each condition and an indented code block. Statements are separated by a elif and else:

if condition_one:
  print("condition 1 met")
elif condition_two:
  print("condition 2 met")
else:
  print('else condition')
Enter fullscreen mode Exit fullscreen mode

Logical Operators

When declaring conditions, we use the following:

Javascript Python
|| or
&& and
!condition not condition

In Javascript:

if (condition1 || condition2) // or
if (condition1 && condition2) // and
if (!condition) // is not
Enter fullscreen mode Exit fullscreen mode

In Python:

if condition1 or condition2 # ||
if condition1 and condition2 # &&
if not condition ## !condition
Enter fullscreen mode Exit fullscreen mode

For Loop

In Javascript, you are required to declare a variable and increment it using the for loop.

In Python we replace that logic with in range(x).

In Javascript:

for (var i = 0; i < 5; i++) {
  console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

in Python:

for i in range(5):
    print(i)
Enter fullscreen mode Exit fullscreen mode

If you want to access an object or item in an Array:

In Javascript:

for (var i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}
Enter fullscreen mode Exit fullscreen mode

In Python:

for obj in arr:
    print(obj)
Enter fullscreen mode Exit fullscreen mode

Types

Primitive data types represent the fundamental values that we can work with in a programming language. JavaScript has 6 types and Python has 4 types:

  • JavaScript data types: undefined, Boolean, String, Number, BigInt, and Symbol.

  • Python data types: Integers (int), Floats (float), Booleans (bool), and strings (str).

To check types in javascript:

type(instance)
Enter fullscreen mode Exit fullscreen mode

To check types in python:

typeof instance;
Enter fullscreen mode Exit fullscreen mode

Imports

Importing files are pretty similar, you just have to swap the order of import and from.

In Javascript:

import React from "react";
Enter fullscreen mode Exit fullscreen mode

In Python:

from django.db import models
Enter fullscreen mode Exit fullscreen mode

Classes

Javascript uses curly braces {} and Python uses colons :.

In JavaScript, the constructor method is called constructor and it has a parameters list as well.

In Python, the constructor that initialises the new instance is called __init__. This method is called automatically when an instance of the class is created to initialise its attributes. It's parameters list defines the values that we have to pass to create the instance. This list starts with self as the first parameter.

Class format

In Javascript:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}
Enter fullscreen mode Exit fullscreen mode

In Python:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
Enter fullscreen mode Exit fullscreen mode

Assign value to a Class

In Javascript:

this.attribute = value;
Enter fullscreen mode Exit fullscreen mode

In Python:

self.attribute = value
Enter fullscreen mode Exit fullscreen mode

Create Class Instance

In Javascript:

personOne = new Person("John", 18);
Enter fullscreen mode Exit fullscreen mode

In Python:

person_one = Person("John", 18)
Enter fullscreen mode Exit fullscreen mode

Summary

The goal of this tutorial is to show the subtle differences between javascript and python. The best way to learn is practice. Try rewriting some of your basic javascript functions in python.

A good way to practice is trying solve a few problems in python on Code Wars.

Thanks for reading and Good Luck!

Top comments (3)

Collapse
 
ivanyhchun profile image
Ivan Chun

Hello Kachi,

Being a JS developer-turned Python developer as well, I appreciate your effort in writing this conversion guide for us. I have been benefitted a lot. However I would like to suggest some room of improvements:

1: for loop

I think the Javascript equivalent should be for...of :

for (const element of arr) {
  console.log(element);
}
Enter fullscreen mode Exit fullscreen mode

Also worth to note that JS use for...of key word instead of for...in because for...in was taken by other function before the usage of for...of in python populated (I read this from internet but can't find the reference).

2: Check type

The correct type checking syntax should be opposite as :
To check types in Javascript:

typeof instance;
Enter fullscreen mode Exit fullscreen mode

To check types in Python:

type(instance)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
arciramona profile image
Gladys Ando

This knowledge on you has got me motivated big time... I've been learning js., css, html and soon the python. I thought I was in the wrong choice. Thank you!

Collapse
 
jules_lewis profile image
Jules

Hi Kachi,

Enjoyed reading your article, but wanted to mention a couple of things.

In Python, every variable is mutable.

That's not strictly true, strings are immutable. You can amend them, but only by re-assigning them (even if it's to the same variable name), and they will be copied to a new location in memory. For example, the following will throw an error:

s = 'Xello world'
s[0] = 'H'   #Error!
Enter fullscreen mode Exit fullscreen mode

The following will work, but s will end up in a different location in memory:

s = 'Xello world'
s = s.replace('X', 'H')
Enter fullscreen mode Exit fullscreen mode

Also, the function to find the type of a variable in Python is type(). Maybe you just have your examples switched, as I think typeof() appears in JavaScript?

Hope this helps,

J