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
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
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
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:
Output
When you want to log something in the terminal or browser. Just change console.log
to print
!
In javascript
:
console.log("hello world");
In python
:
print("hello world")
Comments
When leaving a comment or commenting something out change //
to #
:
In javascript
:
// javascript comment
/* multiline
javascript
comment */
In python
:
"""Python comment"""
# Multi
# Line
# Comment
Variables
There are a couple difference between Javascript
and Python
variables.
-
Javascript
use camel casing andPython
use snake casing. -
const
,let
andvar
forjavascript
. Cases forpython
.
In Javascript
:
var myExample = "hello world"; // global variable
let myExample = "hello world"; // scope variable
const myExample = "hello world"; // unchangeable variable (scope)
In Python
:
my_example = "hello world" # basic variable
MY_EXAMPLE = "hello world" # Red flag to not change
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
inJavascript
are calledlists
inPython
. -
Javascript
use camel casing andPython
use underscores. -
const
,let
andvar
are used injavascript
. Cases are used inpython
.
In Javascript
:
const myList = [4, 5, 6];
In Python
:
my_list = [1, 3, 5]
Functions
Javascript
uses curly braces {}
and function
(or an arrow function
):
function foo(str) {
console.log(str);
}
const foo = (str) => console.log(str);
Python
uses def
followed by a colon :
for their functions:
def foo(str):
print(str)
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");
}
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')
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
In Python
:
if condition1 or condition2 # ||
if condition1 and condition2 # &&
if not condition ## !condition
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);
}
in Python
:
for i in range(5):
print(i)
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]);
}
In Python:
for obj in arr:
print(obj)
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
, andSymbol
.Python
data types: Integers (int
), Floats (float
), Booleans (bool
), and strings (str
).
To check types in javascript
:
type(instance)
To check types in python
:
typeof instance;
Imports
Importing files are pretty similar, you just have to swap the order of import
and from
.
In Javascript
:
import React from "react";
In Python
:
from django.db import models
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;
}
}
In Python
:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
Assign value to a Class
In Javascript
:
this.attribute = value;
In Python
:
self.attribute = value
Create Class Instance
In Javascript
:
personOne = new Person("John", 18);
In Python
:
person_one = Person("John", 18)
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)
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
loopI think the Javascript equivalent should be
for...of
:Also worth to note that JS use
for...of
key word instead offor...in
becausefor...in
was taken by other function before the usage offor...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:
To check types in Python:
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!
Hi Kachi,
Enjoyed reading your article, but wanted to mention a couple of things.
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:
The following will work, but
s
will end up in a different location in memory:Also, the function to find the type of a variable in Python is
type()
. Maybe you just have your examples switched, as I thinktypeof()
appears in JavaScript?Hope this helps,
J