So recently I began working at a little startup in New York City by the name of Underdog.io, where I discovered that they had a back-end written primarily in Python, a language that I had very little previous exposure to.
While I was hired primarily for my experience with JavaScript and React, the small size of our team means that I frequently have to delve into all parts of the codebase in order to ship a feature. So I had to get well acquainted with Python, very fast.
Unfortunately, I had a hard time finding good resources for learning Python that weren't targeted to people who haven't programmed before. I already knew how to program and am familiar with other languages, I just needed to learn the syntax and paradigms of this one specific programming language, Python.
That's where this blog post comes in. To serve as a quick guide for JavaScript developers who want to get up to speed quickly with Python, but without having to learn what declaring a variable means or what a function is.
This post is assuming you are using Python 3.0.1, so some of the examples might not work with older versions of Python.
Syntax
Declaring variables
Declaring a variable in Python is super simple. Like JavaScript, you don't have to set the type of the variable when declaring it. And you don't have to declare the scope of the variable either (let
vs var
):
x = 5
You can change the type of a variable by assigning a value of a different type to it:
x = 5 # x has a type of Integer
x = 'Hewwo' # x is now a String!
Unlike JavaScript, variables in Python are always block scoped.
Blocks
Python is a bit more strict than JavaScript when it comes to syntax. In Python, getting indentation off by a single space can prevent your programming from even running (!). This is because Python uses indentation to create blocks instead of braces. For example, this is how you would define a block in JavaScript vs. Python:
Creating a block in JavaScript
function exampleFunction () {
// This is a block
var a = 5;
}
{
// This is also a block
}
Creating a block in Python
# This is a block with its own scope
def example_function():
# This is also a block with its own scope
x = 5
print(x)
If the line containing print(x)
had one or more extra spaces, the Python interpreter would throw an IndentationError
, because those extra spaces would have created an invalid block.
def example_function():
x = 5
# IndentationError!
print(x)
If that same line had one or more less spaces in it, like this:
def example_function():
x = 5
print(x)
The Python interpreter would throw this error:
NameError: name 'x' is not defined
Because print(x)
is in a block that is out of scope of the one that x
is declared in.
Control flow
if...else
, while
, and for
blocks in Python are very similar to JavaScript:
if...else
if x > 2:
print('hai!')
elif x > 3:
print('bye!')
else:
print('hey now')
if not x:
print('x is falsy!')
while loop
while x > 0:
print('hey now')
for loop
For loops are like JavaScript foreach
loops:
ex_list = [1, 2, 3]
for x in ex_list:
print(x)
Types
Python's type system is a lot like JavaScript's; it's there, but it's not as strict as in other languages like Java or C#.
Practically speaking, variables have types, but you don't have to declare the types of your variables like you would in a statically typed language such as Java.
Here's a quick overview of Python's built in data types:
Numbers
Unlike JavaScript, Python has more than one number type:
- Integers:
1
,2
,3
- Floats:
4.20
,4e420
- Complex numbers:
4 + 20j
- Booleans:
True
,False
You can perform the same operations on numbers in Python as you can in JavaScript. There's also an exponentiation operator (**):
# a = 4
a = 2 ** 2
Lists
Lists in Python are similar to arrays in JavaScript. Lists can contain a mixture of types:
[4, "2", [0, "zero"]]
There's also a special syntax for slicing elements from lists:
a_list = [1, 2, 3, 4, 5]
# 1, 2, 3
a_list[0:2]
# 4, 5
a_list[3:]
# 3, 4
a_list[2, -2]
And some handy built-in methods for operating on lists:
# 3
len([1, 2, 3])
# 3, 2, 1
[1, 2, 3].reverse()
# 1, 2, 3
[1, 2].append(3)
You can even concatenate two lists with the +
operator:
# 1, 2, 3, 4
[1, 2] + [3, 4]
Strings
Strings in Python are a lot like strings in JavaScript. They are immutable, and individual characters can be accessed like elements in an array:
name = 'Mario'
# M
print(name[0])
# Nope, name is still 'Mario'
name[0] = 'M'
Dictionaries
Dictionaries are associative arrays, similar to objects in JavaScript. In fact, dictionaries can be declared with a JSON-like syntax:
# Dictionaries in python
person = {
'name': 'Mario',
'age': 24
}
# Mario
print(person['name'])
Dictionaries have a handy method for returning a default value when trying to get the value of a non-existent key:
# Because `gender` is not defined, non-binary will be returned
person.get('gender', 'non-binary')
None
None
is equivalent to null
in JavaScript. It signifies the absence of a value, and is considered "falsy".
x = None
if not x:
print('x is falsy!')
Functions
Like JavaScript, functions are objects in Python. That means you can pass functions as arguments, or even assign properties to functions:
def func(a, fn):
print(a)
fn()
func.x = 'meep'
# 'meep'
print(func.x)
def another_func():
print('hey')
# 5
# 'hey'
func(5, another_func)
Modules
Modules in Python aren't that far off from modules in ES6.
Defining a module
A module in Python is simply a file that contains some Python code.
# my_module.py
hey = 'heyyy'
def say_hey():
print(hey)
Unlike JavaScript, you don't have to declare what is being exported; everything is exported by default.
Importing a module
You can import an entire module in Python:
# importing my_module.py from another_module.py; both files are in the same
# directory
import my_module
# Do things
my_module.say_hey()
print(my_module.hey)
Or import individual items from a module:
# another_module.py
from my_module import hey, say_hey
# Do things
say_hey()
print(hey)
You can also install modules other people have written with
pip, a package manager for Python.
pip install simplejson
Object Oriented Programming
Python has support for object oriented programming with classes and classical inheritance, unlike JavaScript which has prototypes with prototypal inheritance.
Classes
# Defining a class
class Animal:
# Variable that is shared by all instances of the Animal class
default_age = 1
# Constructor
def __init__(self, name):
# Defining a publicly available variable
self.name = name
# You can define private variables and methods by prepending the variable
# name with 2 underscores (__):
self.__age = default_age
# Public method
def get_age(self):
return self.__age
# Private method
def __meow():
print('meowwww')
# Defining a static method with the `staticmethod` decorator
@staticmethod
def moo():
print('moooo')
# Creating an Animal object
animal = Animal()
# Accessing public variables and methods
print(animal.name)
print(animal.default_age)
print(animal.get_age())
# Accessing a static method
Animal.moo()
# ERR!!!! .__age is private, so this won't work:
print(animal.__age)
Inheritance
Classes can inherit from other classes:
# Inheriting from the Animal class
class Human(Animal):
def __init__(self, name, address):
# Must call the __init__ method of the base class
super().__init__(name)
self.__address = address
def get_address(self):
return self.address
# Using the Human class
human = Human('Mario', '123 Jane Street, Brooklyn, NY 11211')
# Human objects have access to methods defined in the Animal base class
human.get_age()
human.get_address()
Resources
There is a lot more to Python than what's in this guide. I highly recommend you check out the Python docs for tutorials and details about other language features.
And remember, the best way to learn a language is to write it, a lot. So get to coding!
P.S.: If you need an idea for a project, maybe try creating a simple API with Flask?
Top comments (32)
"For loops are like JavaScript foreach loops" Actually they're more like ES6's for of loops: developer.mozilla.org/en-US/docs/W...
Also when creating classes in Python, you should inherit from
object
i.e. class Animal(object)Aren't they exactly like JavaScript's
for...in
loops? developer.mozilla.org/en-US/docs/W...The only difference seems to be Python doesn't do prototypes so you don't have to use
hasOwnProperty
to check the origin of an object's variables"The for...of statement creates a loop iterating over iterable objects (including Array, Map, Set, String, TypedArray, arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property."
In Python you can iterate over iterators or generators. When the end of iteration is reached, an exception is raised that triggers the loop to stop. To me, for..of seems closer to python for..in.
You're right.
for .. in
iterates over key, i.e. it's comparable to something like:whereas
for .. of
iterates over iterables i.e. it's roughly comparable to something like:It's slightly more complicated than that because it implicitly converts some objects, such as Arrays or Maps, to iterables.
JavaScript since ES6 also has generators and iterators that work somewhat similar. There are no exceptions, tho, because iterator interface (that generators also need to adher to in general) returns an object on calls to
.next()
that is of form{done, value}
. Whendone
is false you've reached the end of the iterable.But note that in python
for key in {1: 10, 2: 20}:
iterates over dictionary's keys.You can use
for value in d.keys():
,for (key, value) in d.items():
and (redundant)for k in d.keys():
.These methods exist in both Python 2 and 3, though with some differences (see python.org/dev/peps/pep-3106/).
You can drop the parenthesis i.e.
for k, v in thing.items()
. You only need parenthesis for comprehension i.e.{k: v for (k,v) in thing.items()}
or[(k,v) for (k,v) in thing.items()]
This only makes a difference in Python2, where there was 'old style' and 'new style' classes. In Python3 there'n so difference between
class Animal:
andclass Animal(object):
Also, in 2017 there's little reason to be using Python 3.0.1 when 3.6 is out :)
Python is a very convenient language for programming and scripting. It can be used for creating automated testing frameworks, writing desktop applications, building scripts, system monitoring and logging tools, etc. Usually Python uses such frameworks as Django, Tornado, Flask, Pyramid, Zope, Twisted. Even though Python and JavaScript have a lot of differences, which you have described, it would be a great advantage for JavaScript programmers to learn Python. (mobilunity.com/blog/10-top-framewo...)
Python is a general purpose language like Javascript, I imagine they do all the same stuff coming from a Javascript developer. Everything you mentioned Javascript also already does such as writing desktop applications to building scripts, system monitoring, etc... Javascript also has a large number of frameworks (I'm referring to well maintained projects and frameworks that are a life and time-saver not some of the over polluted ones on npm) - I think it would also be a great advantage for python users to learn Javascript. Both are general purpose scripting languages and both do about the same thing on same platforms with same resources from the community just different ways of going about it.
Furthermore, and I'm open to correction because I could be wrong, Javascript may have better performance because it's almost always partially or completely compiled down to pure machine code while running and additionally some pretty intense optimizations are applied when compiled, some of them downright ingenious. I've seen some Javascript code outperform C++ like by 100 to 1000 times. I'm aware of Python having compiled code as well but as far as I know it's an explicit action you have to take through the command line to first compile it before running it but I'm not sure if the python interpreter actually compiles as it's running or to the efficiency of modern Javascript interpreters.
Regardless though both are heavily used and both have a lot of practicality in most things given their pretty general modular programming languages with a large community behind them so it'd be beneficial for programmers of one language to learn the other.
On the first run, the python interpreter creates „intermediate machine code“. The second run is cached.
Python interpreter doesn't create machine code. The code it creates is called p-code (or "intermediate representation", or "bytecode"). Incidentally the "p" does not stand for Python, but for Pascal, because the concept was first used in UCSD Pascal implementation. At that time majority of interpreters were interpreting the source text directly (which is much slower than parsing into AST or P representation).
However that is starkly different to what modern JavaScript runtimes do. JavaScript is converted to an AST intermediate representation in the first run but in subsequent runs it is compiled in much the same way that C, or Go, for example, are compiled. I.e. all the way to native, binary machine code for the CPU it's being executed on.
This design is based on JVM, and it's called JIT (just in time) compilation. Obviously due to it's dynamic typing systems a lot of object/variable handling is still done by the runtime rather than the direct code (but in many cases JIT optimizes code paths if it can infer it's exclusively dealing with, say, strings), which is why even V8 often executes code slower than, say, HotSpot, even if they both are very optimized JIT VMs.
JavaScripter and Python developer here :)
This article is going directly to my markers. Pretty good and useful! In fact, for newbies who are looking for job opportunities, JavaScript usually is the best option, cause lot of companies are looking for frontend developers and things like Angular, are on the top.
Python now has a lot of opportunities and I think every programmer should learn at least one scripting language, like this fantastic tool. So, congratulations, you have writed a really good transition guide :)
Nice article. I'm also JavaScript developer, that has to write Python code. One difference that is really surprising (and some time annoying) is lack of type coercion. I assumed that if Python is dynamically typed language, when I passed as an argument numer to method that expected string eg. print, Python did the type coercion internally. However, this is not a case. You have to do it explicitly eg. print(str(1))
Yes, this is the most important distinction. This also frustrates many people coming from languages other than PHP to JavaScript.
Namely, both JavaScript and PHP are not just dynamically typed, but also loosely typed in the sense that values are implicitly casted if it's possible, to match the type expected by function call or operator. Furthermore, in JavaScript there are very odd implicit casting rules that cast operands based on combination of the other operand and operator that aren't always intuitive (the
+
operator when either operand is a string comes to mind).Python on the other hand is duck typed, which is a term invented to differentiate it's specific brand of dynamic typing that is not quite strong typing (as it doesn't require explicit interface adherence declaration), but not quite loose typing either (as it doesn't implicitly cast, i.e. it's behavior is more similar to that of, say, Ruby in this regard, than to that of JS or PHP).
Wat? First, why do you call
print
a method? It is a function. Second, it doesn't "expect" a string, it will take whatever you give to it (its signature starts with *args). And third, of courseprint(1)
works, in every Python I know. What exactly did you try to write and what happened?hey! nice and simple article ;)
can I tranlate this to portuguese and post on my blog (with due source link, of course)?
thanks!
Yeah that would be awesome!!
Awesome post, Mario. Thanks for sharing your knowledge with the community! I'm a fan of Josh and everything Underdog.io stands for. I've used them in the past for finding engineering talent at Knotch. Keep up the great work!
If only tutorial books were written like this, great work , helped me get the general gist of the language enough for a confidence that i think i can write this
Correction for Lists section:
doesn't work.
It's same as:
which gives "TypeError: list indices must be integers or slices, not tuple".
Some custom list-like objects, notably NumPy arrays, do support extracting multiple values for multiple indexes. (Except they do this given a list of indixes, as they already interpret tuples for multi-dimensional indexing.)
Anyway, it's not a builtin feature of the language.
Seems to be a mistake on the strings example
Shouldn't
name[0] = 'W'
equal 'M' instead?Nice catch! I must have written one of these lines while upside down.
Nice article! Having recently backed away from learning Python... This presents enough for me to see why it might even be a comfortable place to embrace, being somewhat split between Java"s strict typing and Javascript filmy one. Inspired to go have a look.
BTW
Best. Response. Ever.
Peace
lmao...
short and succinct article!