Python 101 for JavaScript Developers

15 Python things JavaScript developers need to know.

Megan Lo
Python in Plain English

--

Photo by Alex Chumak on Unsplash

Although JavaScript is currently I’m most comfortable with and well-versed in, Python was actually the first language I learned back in college, 3 years ago (by the way, I was a social science student who wanted to explore the STEM field).

Back then, I remember one of my Computer Science peers once told me that Python was considerably an “outdated” language.

Three years later, Python is now one of the popular languages for so many areas, including web development, mobile development, and data science. And frankly, Python is the language that helped build my foundation and made me fall in love with programming.

Credit: Reddit

Now that I don’t remember how to code in Python anymore, I decided to take a free Udacity Python course to refresh my memory (also, Python is part of the requirement for its data structure and algorithm course).

If you are also on a similar path to learning Python as a JavaScript developer, welcome to the Python-JavaScript crossover world, and welcome to this article. Python is also considered an easy language for beginner programmers since its syntax is closer to plain English.

Alright, I’m going to cut my BS. Without further ado, let’s go!

15 Differences Between Python and JavaScript

Since you just started to learn Python, here’s what you have to be aware of coming from a JavaScript background.

  1. No More Semicolons (;)

I actually have seen people not using semicolons in JavaScript. Although sometimes I forget my semicolons too, I personally think adding a semicolon at the end of a line is the same as putting a period at the end of a written sentence. Like, imagine me writing without a period I so want to put a period in the sentence but I am trying to prove a point here. Doesn’t it look super weird?

So yes, in Python, say your farewell to semicolons for now before you go back to writing JavaScript.

2. for i in range (len(object))vs for (let i = 0; i < object.length; i++)

As you can tell, there’s a difference in our for loops. They are equivalent, but JavaScript is more explicit about its for loop by including incrementing the i index in every iteration and the <, while Python tells us the iteration will be within the range of the length of the object. I guess it really depends on which language you are more comfortable with essentially. I am still very used to the JavaScript way.

3. if…elif…else vs if...else if... else

Yes — yes — yes, I know. elif ? Like what is that? Some easy, lazy, and idiotic feature? Just kidding, just kidding. I don’t want to offend the Python community. The if conditional statements are almost the same between the two languages, except for the elif . Well, at least we know this saves us from typing 3 more letters and a space.

4. Say Goodbye to Curly Braces ({})…Unless…

You know how in JavaScript, we always have to use {} to indicate blocks? Not in Python. Python uses the freaking : . Even in Ruby, there is an end to indicate the end of the function. Anyway, here’s what it looks like:

for i in range (len(object)): 
if (object[i] == 'a'):
print("aaaaahhhhh")
elif (object[i] == 'o'):
print("ooooooh")
else:
print("what!?")
# The end of function

I sometimes unconsciously put the {} in my functions and get an error and still have no idea what’s going on (LOL).

However, we would still use {} for what we call an object in JavaScript and in Python, what is a built-in method called dictionary or when creating set (which, in the case of JavaScript, was later introduced in ES2015).

5. print("hello world!") vs console.log("hello world!")

The syntax for printing things on the console is indeed very different. Python is pretty straightforward in terms of that: print this please — sounds dull. Suddenly feeling fancy saying, “JavaScript, please console.log this article!” And don’t forget that console.log is not the only way of printing stuff on the console in JavaScript! — I am feeling some Python attacking me, I haven’t done my research! Please forgive me!)

6. # comment this vs // comment this

That’s the single-line method of commenting in Python and JavaScript respectively. If you are also familiar with Ruby, that’s how you comment in Ruby as well with a #.

And you know what? The # syntax in Python does not work for multi-line comments! For multi-line comments, we have to use '''. Otherwise, we’ll get an error.

# This is a comment
# This is also a comment
# This is also also a comment lol
HEY I AM A COMMENT TOO, WHERE'S MY HASHTAG!?
SyntaxError: invalid syntax

Multi-line comments:

''' 
Hi
This is a comment.
'''

In JavaScript:

/* 
Hello I am a paragraph of comments.
I also know I am way cooler than Python, since I can write a bunch of stuff without worrying about the missing comment syntax in front
*/

Actually, who am I kidding? We can just comment multiple lines with cmd + / , or ctrl + / for Window users.

7. No variable declaration

Yes, you heard me right. If you want to assign a variable in Python:

str = "no variable declaration"

As opposed to JavaScript, where we have to use let and const (technically var as well) and keeping in mind some more rules.

let str = "let is this variable's variable declaration";
const arr = [1, 2, 3, 4, 5];

CONSTANT and const

I included const above because it is one of the ways to declare variables in JavaScript. Python has its own unique way to assign a constant variable, which is USING_ALL_CAPS.

One example would be if you want to calculate the sales tax percentage into your total grocery expenses.

SALES_TAX_PERCENTAGE = 0.095

I know right? Sales tax is expensive in California (LOL).

8. Variable Naming Convention

In Python, snake_case is the conventional way to name a variable while in JavaScript, lowerCamelCase is the conventional way!

Surprisingly, this is one of the few Python things that I didn’t forget from my college years! I guess I like both of them and they both look pretty cool to me!

9. Comparing Values and Types: == vs == /===

In JavaScript, we have a loosely equal to (==) and strictly equal to (===), which compares the values and types of two variables. However, == is the only way for Python to do this sort of comparison. You might think, what if we use = ? Well, just to clarify, this = is the universal way to assign a variable. You probably are thinking back to high school, when we did algebra in math class:

5x + 3 = 7x – 1

Heh, nice try. I wish things were that simple.

10. Logical Operators: and , or , not vs && , || , !

Like I said earlier in the intro, Python is easy for beginners to pick up since its syntax is very close to plain English and this is one of the most obvious examples.

In Python, and , or , not are used as logical operators. What about JavaScript? We use && , || and ! .

Here’s a quick demonstration:

x = 20if (x > 0 and x < 10): 
return True
if (x >= 12 or x <= 20):
return True
if not(x != 20):
return False

11. True and False vs true and false

They serve the same purpose and behavior, except True begins with an uppercase T and the same for False. JavaScript is quite subtle about it. At least in JavaScript, we can save effort on some pinky-reaching action to the shift key!

12. None vs null , as well as None vs undefined

In Python, None is used to indicate no value is assigned at that point of the program, which is kind of similar to null in JavaScript. In JavaScript, null represents the “intentional absence of any object value” (MDN).

Despite the similarities, since a variable cannot be assigned to nothing in Python, None can be assigned to substitute the absence value, while we can declare a variable in JavaScript without a value: let x;.

And this would return undefined , which indicates a variable is declared but no value is assigned.

13. Primitive Data Types in Python vs JavaScript

Since Python was my first programming language, this still kind of remained stuck in my head when I learned other languages like JavaScript later on. I am still surprised that there is no so-called float (i.e. decimal numbers) in JavaScript. I still have to Google it sometimes.

Speaking of which, Python has 4 primitive data types: int , float , bool and BigInt and JavaScript has 7 primitive data types: number , string , boolean , bigint , symbol, undefined and null .

Although JavaScript has more primitive data types, I actually really like Python’s float because it’s very clear when a decimal number is used. I guess that’s one of the reasons why Python is very popular in data science

14. type vs typeof

Speaking of data types, let’s talk about how to find out the types of variables!

type is used in Python while typeof is used in JavaScript.

Here are some simple examples:

# Python
x = 2.5
type(x)
# <class 'float'>
// JavaScript
const x = 2.5
typeof(x)
// 'number'

15. List vs Array (and a little talk about tuple)

This is quite confusing, even for me. In Python, it’s called List which is known as Array in JavaScript.

List can do the same thing as an array . It can be sliced, modified, indexed, and used in the program.

Built-in list methods like: index() , slice() , append() , pop()

Full list of list methods here on W3School.

As a JavaScript developer, you probably are wondering what a tuple is. I was confused too. Here’s a quick breakdown:

  • tuple : can be used but immutable, i.e. you can’t change a thing in tuple once you call it.
  • list : can be used and can be modified.

You will see a tuple with an optional () while list , similar to array , with [] .

But since tuple cannot be modified, it does not have as many built-in methods as list . Not even adding or deleting. I will attach some easy-to-read and understand resources at the end of this article!

A practical example here that combines most of the things you learned from above:

# Python
# Check whether all elements in the array are int.
list = [ 1, None, 'javascript', 2.5, 4, 3 ]
def check_int(list):
for i in range (len(list)):
if (type(arr[i]) != 'int'):
return False
return True
print(check_int(list)) # False
// JavaScript
// Check whether all elements in the array are number.
const arr = [ 'python', null, 'javascript', 2.5, null, 3 ];
function checkNumber(arr) {
for (let i = 0; i < arr.length; i++) {
if (typeof(arr[i] !== 'number')) {
return false;
}
}
return true;
}
console.log(checkNumber(arr)); // false

Bonus: ordered and unordered collection of objects

This is something new to JavaScript developers. In the last point before the example, we talked about list and tuple . We also briefly discussed set and dictionary when talking about objects{} (If you understand set in JavaScript, this should be no problem for you). These two pairs have one big difference, which is ordered and unordered .

ordered and unordered are something that are thrown around a lot in Python and it’s one of the important concepts to understand. You might wonder does it mean sorted and unsorted? That’s what I thought, but it turns out ordered and unordered is referring to whether the output of these data structures would have a defined order or not. What does it mean?

Elements in list and tuple , which are an ordered collection of objects for instance, can be accessed easily, since each element has its designated index.

On the other hand, for set and dictionary , orders are not guaranteed.

Since I am still learning at the moment, I would use the example that I found from my source to demonstrate. In this example, we would transform a very long string to list , tuple and set .

Input with ASCII letter:

Remember if we implement sort() in a JavaScript array with ASCII letters in ascending order, it would never be sorted from ‘A-Z’, since each ASCII letter has its Unicode number. That’s why this is a perfect example to demonstrate.

letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

Here are the variables that represent each collection:

string_letters = str(letters)
lists_letters = list(letters)
tuples_letters = tuple(letters)
sets_letters = set(letters)
print("String: ", string_letters)
print() # for new line
print("Lists: ", lists_letters)
print() # for new line
print("Tuples: ", tuples_letters)
print() # for new line
print("Sets: ", sets_letters)

And here’s our output:

String:  abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

Lists: [
'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z', 'A', 'B',
'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z'
]

Tuples: (
'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z', 'A', 'B',
'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z'
)

Sets: {
'G', 'U', 'P', 'K', 'Q', 'w', 'I',
'Z', 'N', 'l', 'm', 'h', 'J', 'D',
'k', 'C', 'r', 'B', 'A', 'F', 'y',
'c', 'V', 'i', 'E', 'a', 'o', 'R',
'T', 'e', 'g', 'b', 'L', 'f', 'X',
'x', 'O', 'S', 'j', 'v', 'p', 'Y',
'H', 'u', 'n', 'z', 't', 'M', 'd',
'W', 's', 'q'
}

As we can see, list and tuple have the same exact order as the original string, but not set .

To once again show that Set/Dictionary is an unordered collection of objects, I also ran the same string on my console, and here’s what I got:

From my console

If you compare my result to the one above, the orders are completely different.

Before You Go…

Woohoo, you made it! Those are the 15 things you have to know when switching from JavaScript to Python. There are still a lot of things I haven’t had a chance to talk about, like defining a class in JavaScript and Python. But those are slightly more advanced topics than what we talked about today.

Let’s recall what we learned:

  • No more semicolons :(
  • No more curly braces for blocks :(
  • No more double slash for comments :(
  • No more variable declarations :(
  • Fewer primitive data types :(
  • snake_case and lowerCamelCase :(
  • More complicated data structures, like tuples :(
  • ordered and unordered

I am totally kidding with the sad emoji. I want to show much love to both communities since we actually are more similar than we think.

Hope you made some good takeaways from this article. And I’ll be sure to talk about comparing JavaScript and Python string methods in my next article.

Stay tuned!

Resources

Python in General

Ordered and Unordered

Python Data Structures

More Tuple

Something interesting that I didn’t talk about in this article:

When to Use Single Quotes and Double Quotes (conventionally speaking)

Difference Between List and Tuple

10 Examples to Master Tuples

I took some references from this awesome freeCodeCamp article:

More content at plainenglish.io

--

--