Walrus Icon

The Coding Walrus

Python to JavaScript Basics

Python to JavaScript Basics

Moving from JS to Python is not a very daunting move to make, however there are a few base concepts in Python that are radically different from JavaScript. We will be talking Python in JavaScript terms, creating a python guide for JavaScript developers. In the basics we will go over Python variables, indentation, if, else, elif, list, range, tuple, and for loops. If you have a fair grasp of JavaScript and are dabbling into python, this will be a great tool for you. Understanding the basics will set the foundations for understanding more advanced concepts as well as the inner workings of the language.

Variable Declaration

In Python, you don't have to declare the kind of variable that you are creating. There are no var, let, or const:

x = 'hi'
print(x) #hi

x = 1
print(x) #1

x = True
print(x) #True

Here we can see a few things:

  • Variables are declared with the format variableName = value
  • Variables can be re-assigned to any value after declared (This includes more complex types)
  • Booleans are Capitalized.
  • print() is the equivalent to console.log()
  • Comments are done using hash symbol #

Variable Types

JS has primitives which are values that are not objects. In Python everything is an object. However, every object has a type, and there is no object type. We can check types using the type() function:

x = 'hi'
print(type(x)) #<class 'str'>

x = 1
print(type(x)) #<class 'int'>

x = 1.1
print(type(x)) #<class 'float'>

x = True
print(type(x)) #<class 'bool'>

We can see that they all have different types, determined by their class: string, integer, float, boolean. In JavaScript we have 1 number type (equivalent to double in other programming languages), with the exception of the new BigInt type. The int type is for positive or negative whole numbers, the float type is for any number containing one or more decimals.

Being explicit with your type

Since all the types are classes, you can be explicit by using their constructor function:

x = str('Hai')
print(x)#Hai
x = int(1)
print(x)#1
x = float(1)
print(x)#1.0
x = bool(True)
print(x)#True

It will also try to convert a value to the type that you are creating, for example converting the int 1 into the float 1.0. This won't make the variable immutable, it is the same as declaring it normally and these constructors are mostly used to convert values.

if statement and Indentation

Python does not use curly braces for scoping. Python uses indentation which separate code blocks:

x = 2

if x == 2:
    print('x is the number 2')#x is the number 2
if (x == 2):
    print('x is the number 2')#x is the number 2
if (x == 2):
print('x is the number 2')#IndentationError: expected an indented block

Statements in python don't need brackets, but they can still use them. The indentation tells Python that the code after the if statement belongs to the scope of that if statement. If we don't indent, we will get an indentation error. The standard indentation is 4 spaces, but Python will not harass you if you want to do any other number of spaces as long as it is consistent with your code block when indenting:

if (x == 2):
  if(x == 2):
      print('hai')
   if(x==2):#IndentationError: unindent does not match any outer indentation level
      print('hai')

Basic Logical Operators: ===, &&, ||, !

Python uses keywords for logical operators instead of symbols:

x = True
y = True
z = False

if x and y:
    print('Both True') #Both True
if x is True:
    print('x is True') #x is True
if x == True:
    print('== works as is as well') #== works as is as well
if x and z:
    print("Won't print")
else:
    print('x and z are not both True.')#x and z are not both True
if x or z:
    print("x is True, overrides z being False") #x is True, overrides z being False
if not z:
    print('The opposite of False is True')#The opposite of False is True
if x and not z:
    print('The opposite of z is True') #The opposite of z is True

Each keyword corresponds to the operator it is called after. You can mix and match them as we did with and not. We sprinkled in an else, which only corresponds to the if statement it followed.

Difference between 'is' and ==

Comparing what would be primitive values in JS we have loose equality ==, and strict equality ===. In Python there is only equality (how nice), which means that you will get a lot of mistakes starting out by doing triple equals everywhere. To explain the difference between is and == equals, we will jump the gun a little:

a = [1]
b = [1]

if a is b: print('a is b')
else: print('a is not b') #a is not b

if a == b: print('a equals b') #a equals b

if a is not b: print('a is not b') #a is not b

if a != b: print('a is not equal to b')
else: print('a is equal to b') #a is equal to b

if a not == b: print('a is not equal to b') #SyntaxError: invalid syntax

I threw 2 curve balls here, we created a list which is the equivalent to an Array in JavaScript, and we also wrote if and else as one liners. This is valid as long as we are doing one thing after the statement. is is used to compare location in memory. == is used to compare values. They cannot be mixed and matched. A caveat being that is will return true for what we would consider JS primitives, even though they are objects.

  • and, or, not are logical operators that replace &&, ||, !
  • == compares values and is a comparison operator.
  • is compares location in memory and is an identity operator.

elif replaces else if

In Python, else if is replaced by elif, which works in the same if statement if the indentation is done correctly:

a = 3

if a == 1:
    print('a is 1')
elif a == 2:
    print('a is 3')
elif a == 3:
    print('a is 2') #a is 2
else:
    print('a is not a number between 1 and 3')

Python Array Equivalents: List, Tuple, and Range

In JavaScript we have two main object data structures: objects and arrays, in python we have plenty more. We will start with sequence types or collection data types which are equivalent to arrays and are list, range, and tuple.

List

list1 = [1,2,3,4]
list2 = [5,6,7,8]
mixedWithAppend = list(list1) #Creates a copy


print(list1[0])#1
print(list1[-1])#4
print(list1[-2])#3
mixedList = list1 + list2
print(mixedList)#[1, 2, 3, 4, 5, 6, 7, 8]

print(mixedWithAppend.append(list2)) #None
print(mixedWithAppend)#[1, 2, 3, 4, [5, 6, 7, 8]]

We can create a list using the same JS syntax for arrays, comma separated values. We can also create them using the list() function, which needs to have a list passed as its argument. Here we used list() to create a copy of list1. We can access values from a list with bracket notation just like in JS, however we can pass negative values for the index to access values from the end of the array downwards. Which is equivalent to doing JS array[array.length-1] without the added boilerplate.

Unlike JS, we can use the + operator to concatenate two lists. In JavaScript using the + operator converts the values to strings. Python lists have the append method which is the equivalent to JS Array's push method. We can see that we appended the whole list as the last value in our mixedWithAppend variable. To use append as the + operator we would need to loop through the items and append them one by one. Another thing of note is that the append method does not return the appended array and instead returns None. Therefore we need to use append and then print the list after calling the method.

The JavaScript equivalent to adding lists would be:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

console.log([...arr1, ...arr2]); //[ 1, 2, 3, 4, 5, 6 ]

Length, Slicing, and Other Methods

Python has less list methods than JS has Array methods. Python has equivalents for all the main mutating JS array methods, however Python has a built in slicing syntax using bracket notation:

list1 = [1,2,3,4]

print(list1[1:3])#[2, 3]
print(list1[:3])#[1, 2, 3]
print(list1[1:])#[2, 3, 4]
print(list1[::2])#[1,3]
print(list1[1:4:2])#[2, 4]

This is called specifying a range of indexes, and is the equivalent of using JS' slice method. It can take up to 3 arguments? or values and has the following structure: [startIndex: endIndex: step], which have the following default values: [0:endIndex:1]. The step value will determine if how much items it will skip when returning the new list.

Python lists do not have properties, meaning that they don't have the .length we use frequently in JS. Instead, we get the length using the len function:

list1 = [1,2,3,4]

print(len(list1))#4

Spread Operator

The JS equivalent to the spread operator in python is called unpacking and is done by using the asterisk before the variable name:

list1 = [1,2,3,4]

print(*list1)#1 2 3 4

Tuple and Range

A python Tuple is an ordered collection that is unchangeable:

tuple1 = ('a','b',3,5)

print(tuple1)#('a', 'b', 3, 5)
print(tuple1[1])#b
print(tuple1[1:4])#('b', 3, 5)
print(*tuple1)#a b 3 5
print(type(tuple1))#<class 'tuple'>
print(tuple1.append(4))#SyntaxError: expression cannot contain assignment
print(tuple1[0]=10)#SyntaxError: expression cannot contain assignment

The syntax for tuples is like lists but uses brackets, the difference is that we cannot assign any new value to the tuple or append like you would be able to do in JavaScript const arrays using push. A tuple is truly constant, with one big caveat: they can be re-declared:

tuple1 = (1,2,3)
print(tuple1)#(1, 2, 3)
tuple1 = (4,5,6)
print(tuple1)#(4, 5, 6)

Ranges create sequence of numbers through the range constructor using the following syntax: range(start, stop, step):

range1 = range(1,5)

print(range1)#range(1, 5)
print(range1[1])#2
print(range1[1:3])#range(2, 4)
print(*range1)#1, 2, 3, 4
print(type(range1))#<class 'range'>
print(range1[1] = 5)#SyntaxError: expression cannot contain assignment

The stop argument will not include that number in the range. We can see that the syntax is different, when we print we get the constructor we used. However it behaves like a list when accessing values with bracket syntax and unpacking, however when we specify a range of indexes we get a range constructor as a return value. When you need a list or iterable of only numbers, range is your best bet. Ranges cannot get values assigned to them, making them a tuple of numbers.

Summary for Array Equivalents

  • List is the most similar to JS Arrays.
  • Tuple is an immutable list and uses brackets as its syntax.
  • Range is a tuple of numbers.

For Loop and Iterables

In Python the for loop is not like a for loop in other languages, and it only works to iterate over iterable data structures. You can only use for to iterate over a list, tuple, range, dictionary, set, or string. A vanilla for loop in python would look like this:

for i in range(3):
    print(i)
# 0
# 1
# 2

Since we need an iterable to use for, we have to create a range, this is the equivalent of doing the following in JavaScript:

for (let i = 0; i < 3; i++) {
	console.log(i);
}

The pattern of the Python for is like the JavaScript for...of and for...in loop combined. It uses the for...in syntax but it works in absolutely every iterable data structure.

Break and Continue Statements

As with the JS break we can stop the loop before it has gone through all the items:

list1 = [1,2,3,4]

for n in list1:
    if(n == 3):
        break
    print(n)
#1
#2

Code after the break statement will not execute and the iteration will stop. continue stops the current iteration of the loop, and continues with the next iteration:

list1 = [1,2,3,4]

for n in list1:
    if(n == 3):
        continue
    print(n)
#1
#2
#4

Here we used continue to jump into the next iteration before hitting print(n), which made us skip printing 3.

for...else

We can use the else keyword at the end of a for loop to execute a block of code when the for loop is finished:

list1 = [1,2,3,4]

for n in list1:
    print(n)
else:
    print('I am done!')
# 1
# 2
# 3
# 4
# I am done!

Here we executed a block of code after the for finished. How would this behave when using break?

list1 = [1,2,3,4]

for n in list1:
    if n == 3:
        break
    print(n)
else:
    print('I am done!')
# 1
# 2

If we break out of a loop, the else statement is not executed.

pass statement

In Python a for loop cannot be empty, therefore if we need to comment the code out or just execute a for loop with no content, we must use the pass statement to avoid an error:

list1 = [1,2,3,4]

for n in list1:
    pass
else:
    print('I am done!')
#I am done!

Here we did nothing in the for loop and finished it which is why we executed the code block in the else statement.

Strings as Iterables

Strings in python behave like tuples in that they are iterable, can be accessed using bracket notation, you can use range of indexes on them, but you cannot assign values using bracket syntax:

word = 'bird'

print(len(word))#4
print(word[1])#i
print(word[1:4:2])#id

for letter in word:
    print(letter)
# b
# i
# r
# d
word[1] = 'b'#TypeError: 'str' object does not support item assignment
  • For loops in python only work to iterate over iterables.
  • Use break to end a for loop prematurely.
  • Use continue to skip part of a loop and jump to the next iteration.
  • You can use else to execute code once a loop concludes.
  • Strings are iterables that behave like tuples in iteration rules.

Conclusion

We went over the basic differences between Python and JavaScript. In Python everything is an object but there is no object type. Python uses indentation for scoping in what are called blocks. Python does not have variable kinds but it does have plenty of variable types and every variable in python can be re declared. In Python if doesn't require brackets, and else if is elif. Python uses keywords for logical operators and does not use ===. Memory location equality is done using is and value equality is done using ==. We went over 3 collection data structures that are similar to JS Arrays with a few differences. And finally we talked about how for loops only work on iterables like for...of and for...in JS loops. I hope this helped you get the basics for learning Python coming from JavaScript.