DEV Community

Cover image for From Javascript to Python
Avery Berkowitz
Avery Berkowitz

Posted on

From Javascript to Python

So you know javascript but you get this amazing offer to work at this great company in the perfect city and JS is nowhere to be found in their tech stack. Instead, they use the Python-based Django web development framework. So where do you start? In this post, I will (hopefully) lay that foundation. We will cover:

  1. What is python?
  2. Why learn python?
  3. Basic(simple) datatypes
  4. Lists
  5. Variable declaration
  6. Writing functions

It is expected that the reader is familiar with javascript so if that isn't the case, I recommend checking out this intro to python on Udemy where no prior programming knowledge of any kind is needed.

What is Python?

From their website: Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. What?? Yeah, that's what I thought the first time I read it, so let's break that sentence down:

  1. interpreted - just like javascript, Python is translated directly into code that a computer can read. In javascript, this is usually handled by an interpreter like Chrome's V8 engine or Node.js on our computer or server. Python has it's own interpreter that can be downloaded here.
  2. object-oriented refers to the way a Python program is organized/structured. We use classes and objects in python to separate concerns, DRY up our code, and allow our programs to represent things in the Real World. In contrast, Javascript is a functional programming language and uses functions to accomplish many of the same organizational strategies as Python. Conceptually, there is a ton of overlap here that we could discuss for hours. Coming from javascript, just know that a Class in Python is not a special type of function like it is in Javascript.
  3. high-level programming language - this refers to languages that are more comparable to human languages. Basically, it is easy to read, even for non-programmers. Javascript also is a high-level language though I would argue that it is not quite as easy to read compared to python. We will revisit this comparison with code examples in a bit.
  4. dynamic semantics - basically, we can assign and reassign variables to point to different values and datatypes. We can do this in javascript as well.

Why Python?

According to Stack Overflow, it is the fastest growing programming language. Python ranked 4th in most popular technology in the 2019 Developers Survey on stack overflow.
Alt Text

Basic (Simple) Datatypes

Time to see what Python is all about. To try out any of the following code examples, I recommend using repl.it or you can download the python interpreter. We will be using python's built-in type() function for type-checking. This is the equivalent of javascripts typeof. To log values upon execution, we use python's console.log equivalent print()

  • In javascript, we just have numbers. Python breaks numbers into three categories: Ints, Floats, Complex Numbers.
# int
print(type(10))
# >>> <class 'int'>

# float
print((type(10.11)))
# >>> <class 'float'>

# complex
print((type(10 + 5j)))
# >>> <class 'complex'>
  • Strings and booleans are really similar to javascript. Notice that booleans are capitalized in python.
print(type("I am a string"))
# >>> <class 'str'>

# float
print((type(True)))
# >>> <class 'bool'>
  • None datatype. There is no null or undefined in python. Instead, we have None
print(type(None))
# >>> <class 'NoneType'>

also notice that comments are written with # in python compared to // in javascript

Lists and other complex datatypes

A list in python is pretty much exactly like an array in javascript. Values (elements) are contained within [] and comma-separated. We can also use bracket notation for access.

my_list = [1,2,3,4]

print(my_list[2])

# >>> 3

Note that elements in a list may NOT be separated with spaces and like in javascript, a list is zero-indexed.
Other complex datatypes include:

  • tuples: immutable lists my_tuple = (1,2,3,4)
  • sets: unordered (not indexed) lists my_set = {1,2,3,4}
  • dictionaries: equivalent to objects in javascript (key-value pairs)
my_dictionary = {
  "name": "Avery",
  "age": 32,
  "city": "New Orleans"
}

print(my_dictionary["name"])

# >>> Avery

Variable assignment

When writing variables in javascript, we have quite a few choices to make. Should we use const, let, var, or define a global variable without a keyword (never do this...)? Well in python, we don't use any keyword, ever. Convention for naming variables is to use snake case. And just like javascript, variables are case sensitive.

my_dog = "Jasmine"
x = 10
X = 100

print(my_dog)
print(x)
print(X)

# >>> Jasmine
# >>> 10
# >>> 100

Writing functions

Functions in python are written with the def (short for define) keyword. Unlike javascript, we use indentation to define the function body (no mustache brackets here!). The norm is an indentation of 4 whitespaces, but you may indent however you like as long as you are consistent.

def multiply_by_two(x):
    print(x * 2)

multiply_by_two(30)

# >>> 60

What next?

Clearly, we have just scratched the surface of Python. But as you can see, it shares many similarities with javascript. Javascript developers familiar with ES6 Class syntax will be right at home when working with python classes. Moving forward, I highly recommend Colt Steele's The Modern Python 3 bootcamp. The saying goes that learning your first language is always the hardest -- that certainly was the case from me as picking up python after javascript has been a smooth ride so far. Best of luck on your python journey!

Top comments (14)

Collapse
 
kurisutofu profile image
kurisutofu • Edited

One thing that could be added is that when updating a global variable from a function, the variable needs to be declared as global in the function.

outerVar = "not assigned"

def assign():
   global outerVar
   outervar = "Assigned"
Collapse
 
jannikwempe profile image
Jannik Wempe

Good hint, but in my opinion it doesn't belong to this kind of introduction to python, because it is (in most cases) bad practise. The "normal" case should be to use parameters and return a value.

Collapse
 
kurisutofu profile image
kurisutofu

Well, he introduced variables and functions, so I think it's worth mentioning because should they want to use it, they may think they are used the same way as many other languages and wonder why the variable is not updated.

Since this is geared to people coming from Javascript, I'm assuming they already know when or when not use a global variable.

Thread Thread
 
jannikwempe profile image
Jannik Wempe

Okay, good points, thanks. The argument, that people should already know what they are doing, convinced me. So maybe, yes, it is worth to mention it.

Collapse
 
dmerejkowsky profile image
Dimitri Merejkowsky

we use classes [...] to allow our programs to represent things in the Real World.

Sorry, but I could not resist. I think as developers we must be very careful with this statement.

I've explained why in my two part series

Collapse
 
kurisutofu profile image
kurisutofu

I believe it's not "touples" but "tuples".

I recently started using python (even though that was the language that introduced me to programming) from a javascript and C# background.
I somehow found it disconcerting at first and I had to do basically what you wrote. I had to check how things work in python.
I think a post like this can be useful so thanks for writing it!

Collapse
 
aveb profile image
Avery Berkowitz

yes, definitely tuples. thanks for the catch

Collapse
 
waylonwalker profile image
Waylon Walker

Very cool to see an inverse perspective to mine. I started in Python before moving to JavaScript. Thanks for sharing.

Collapse
 
juancarlospaco profile image
Juan Carlos

I started in Python2 before moving to CoffeeScript for JavaScript.
Then back to Python3, then CoffeeScript kinda fading away slowly,
then tried TypeScript but didnt like it and wont work for me.
Then learned Nim which covers JavaScript and WebAssembly now.

JavaScript does not really feel like a pure Functional language tho.
Good post, keep it up.

Collapse
 
mateiadrielrafael profile image
Matei Adriel

Same

Collapse
 
robertomaurizzi profile image
Roberto Maurizzi

Well, it's much better than moving the other way around like I'm doing: less node_modules 'black holes' since you can do basic things like deep-copying objects out of the box and the language works without transpiling the heck out of it... 😂
I guess you'll still have much JS on the frontend that uses Django to access APIs created with Django REST Framework.
I'm curious, do you use any "DRY" approach/library so that you don't have to write the same checks in both Python and JavaScript?

Collapse
 
mateiadrielrafael profile image
Matei Adriel

You gotta try out pnpm! Its like npm but it doesnt install things more than once per machine:)

Collapse
 
blackr1234 profile image
blackr1234 • Edited

This is the equivalent of javascripts typeOf().

Should be typeof operator or typeof(...) (lowercase o) function.

Useful article though.

Collapse
 
aveb profile image
Avery Berkowitz

thanks for the catch. moving too fast today!