This page looks best with JavaScript enabled

Intro to Python for JavaScript developers

 ·  ☕ 11 min read  ·  ✍️ Iskander Samatov

python intro for javascript developers


Python is a popular language that appeals to many people due to its concise syntax and the ease with which you can perform various kinds of data manipulations. It is the predominant tool in the sphere of data science. Its rich ecosystem of packages and concise syntax make it an excellent choice for scientific computations.

I started learning Python to learn data science and ML, but since I already have programming experience, especially with JavaScript, I did not need to learn basic programming concepts from scratch and was mostly interested in the syntax and nuances of the language.

So to help others in the future, I wrote this Python introductory post for people with prior programming knowledge that will provide an introduction to Python and compare Python with JavaScript.

Basic Python Syntax

Let’s start with the basic syntax.

Just like JavaScript, Python is a dynamically typed language, which means you do not need to declare the type of the variable when creating it. You can start by simply typing the variable name and assigning a value:

1
2
3
  name = "John Doe"
  name2 = 'Jane Doe'
  zipCode = 56319

Notice that you can add your string values using either single or double quotes, the same as in JavaScript.

Python has all of the same primitive types as any other language: strings, booleans, integers, floats, and others. So it’s not really worth going over them. But I do want to note a couple of curiosities I noticed:

  • The keywords for true & false in Python are capitalized like so:
1
2
  isTrue = True
  isFalse = False
  • You can use the built-in function type to derive the type of the variable.
1
2
num = 42
print(type(num))  # Output: <class 'int'>
  • Unlike JavaScript, you cannot simply concatenate strings and numbers in Python. Concatenating strings with other primitive types requires wrapping them with a str() function:
1
2
  temperature = 90
  label = "The temperature is " + str(temperature) + " degrees!"

Lists

Basics

Lists in Python are the equivalents of arrays in JavaScript. Same as JavaScript arrays, Python lists allow storing elements with different types:

1
2
3
  person_info = ["John Doe", 1989, True, "Seattle, WA"]
  new_info = []
  another_list = list()

As you noticed, you can simply use brackets to initialize a list. You can start with an empty list or initialize it with some existing data. Another alternative is to use the built-in list() function to initialize a new list.

Advanced List Operations

Now let’s delve deeper into some of the operations you can perform with Python lists.

Just like JavaScript arrays, you use indexing to access elements at a certain position:

1
2
  person_info = ["John Doe", 1989, True, "Seattle, WA"]
  age = person_info[1]

However, one additional neat thing about indexing with Python lists is that you can use negative index values to access elements from the end of a list. So, for example, here’s how I can access the last element from the list above:

1
2
  person_info = ["John Doe", 1989, True, "Seattle, WA"]
  city = person_info[-1] # "Seattle, WA"

And I’m not limited to only accessing the last element. If I used person_info[2], it would return the second-to-last value, which is a boolean True, and so forth.

You can also reverse and look up an index of a given value in a list. To do that, you would use the list’s index method:

1
2
  person_info = ["John Doe", 1989, True, "Seattle, WA"]
  year_index = person_info.index(1989) # 1

Slicing is a similar concept in Python and JavaScript. It allows you to select sub-lists inside of a list within the provided range. In Python lists, the slicing syntax is very concise and intuitive. For example, here’s how you can use it to get a copy of a list containing the first 3 elements:

1
2
  birthdays = [1994, 1987, 1995, 1995, 1978, 1990, 1992, 1983, 1987, 1999]
  first_3_birthdays = birthdays[0:3] # [1994, 1987, 1995]

One thing to keep in mind: in this syntax list[start:end], start is inclusive while end is exclusive.

Start and end values are not required with slicing. You can leave them out like so: list[:end] or list[start:]. In the first example, Python will assume that you want to start from the first item of the list, so it will read it as list[0:end]. In the second example, as you might’ve already guessed, Python will assume that you want to copy items from the start position to the end of the list, so it will read the command as list[start:len(list)].

You can actually leave out both start and end values when slicing to get a full copy of a list:

1
2
  list_copy = birthdays[:]
  list_copy2 = list(birthdays)

Alternatively, you can use the list() function to create a copy.

Another powerful aspect of slicing in Python is updating a range of values in a list using the assignment operator:

1
2
3
  my_list = [1, 2, 3, 4, 5]
  my_list[1:3] = [8, 9]
  print(my_list)  # Output: [1, 8, 9, 4, 5]

In the code above, we’re updating the values of the second and third elements of the list in a single command.

It’s similarly easy to concatenate lists in Python. You can simply use the + operator. The result is another list with combined values:

1
2
3
4
  first = [1, 2, 3]
  second = [4, 5, 6]
  combined = first + second
  print(combined) # Output: [1, 2, 3, 4, 5, 6]

Dictionaries

Just as Python lists are equivalents of JavaScript arrays, dictionaries are equivalents of JavaScript maps. The syntax for dictionaries is also very similar. You create them with curly brackets and provide key-value pairs, separated by commas. You can access values in dictionaries using the familiar ["key"] syntax:

1
2
  person = {"name": "John Doe", "birth_date": 1989, "is_married": True, "city": "Seattle" }
  print(person["name"]) # "John Doe"

Dictionaries have handy keys() and values() methods that return the list of dictionary keys and values.

To check if a certain key is present in a dictionary, you can use the in operator:

1
  print("name" in person) # True

Same as with lists, you can use the del() function to remove items from dictionaries.

When it comes to data types that can be used for keys, Python is again more lenient. In JavaScript, you can only use strings or symbols as keys for objects. Even if you use other data types, they will automatically get converted to strings. With dictionaries, you can have different data types as keys, like numbers or tuples, as long as they are immutable. Mutable types like lists are not allowed to be used as keys for dictionaries.

Same as in JavaScript, in Python, you can nest dictionaries to create more complex data structures. And you can chain square brackets to access nested elements in a dictionary:

1
2
  nested_dict = {"outer": {"inner": "value"}}
  print(nested_dict["outer"]["inner"])  # Output: "value"

Control Flow

If Statements

A key feature of Python is that spacing determines the execution flow of the code. To mark lines of code that belong to different control flow pieces or functions, you use indentation. For example, here’s how you would write an if/else statement:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
  name = "John Doe"
  name2 = 'Jane Doe'
  zipCode = 56319
  married = True
  filing_status = "Unknown"

  if married:
    filing_status = "Joint"
  else:
    filing_status = "Single"

Notice also how in Python you don’t need to wrap statements with parentheses; you simply need to finish your statement with a colon :.

Workaround

However, there is a workaround if you would like to place multiple commands on the same line. You can separate them with ;:

1
  print(name); print(name2);

Loops and Iterations

The while loop is the first loop we’ll take a look at:

1
2
3
4
  count = 0
  while count < 5:
    print(count)
    count += 1

Same as with if statements, you use indentation to define the blocks of code that need to be executed inside the loop.

Python provides the for in loop to iterate over lists or dictionaries. When using the for in loop to iterate over a list, you can use the enumerate function, which returns an iterable with an index and the corresponding item from a list:

1
2
3
  my_list = ['a', 'b', 'c']
  for index, value in enumerate(my_list):
    print(index, value)

Similarly, you can use the for in loop to iterate over elements in a dictionary. In that case, you need to use the .items() method on a dictionary:

1
2
3
  my_dict = {'a': 1, 'b': 2, 'c': 3}
  for key, value in my_dict.items():
    print(f"Key: {key}, Value: {value}")

Error handling

Error handling in Python is managed with the try, except, and finally statements. Here’s the basic syntax:

1
2
3
4
5
6
  try:
    result = 10 / 0
  except ZeroDivisionError as e:
    print("An error occurred when dividing by 0")
  finally:
    print("This code runs no matter what.")

The try block contains the code that might throw an exception. If an exception occurs, the code in the except block will execute. The finally block contains code that will always run, whether an exception occurred or not.

You can handle multiple exceptions by using multiple except blocks:

1
2
3
4
5
6
  try:
    result = 10 / 0
  except ZeroDivisionError as e:
    print("An error occurred when dividing by 0")
  except ValueError as e:
    print("Value error")

This way, you can handle different types of exceptions separately and provide specific error messages for each type.

It’s also possible to raise your own exceptions using the raise keyword:

1
2
3
4
5
6
7
8
9
  def check_positive(number):
    if number < 0:
      raise ValueError("Number must be positive")
    return number

  try:
    check_positive(-5)
  except ValueError as e:
    print("Value error")

In this example, the check_positive function raises a ValueError if the input number is negative, and the except block handles this error by printing an error message.

This section covers the basics of error handling in Python, giving a brief overview of how to use try, except, and finally statements to manage exceptions in your code.

Functions

Let’s briefly touch on the basics of declaring functions in Python. Here’s what the syntax looks like:

1
2
3
  def function_name(parameters):
    # function body
    return value

As I mentioned earlier, in Python, you use indentation to group code that belongs to a function. To declare a function, you type the def keyword, followed by the function name and parameter list. To return values from a function, you would use the return keyword.

Now let’s cover some of the commonly used built-in functions in Python:

  • max(list) returns the highest value in a list.
  • round(number) is used for rounding numbers.
  • help(functionName) provides an interactive display that can be used to get information about modules, functions, and others. The information comes from the documentation comments in the code.
  • len(list) returns the length of a list.
  • del(item) is used for deleting items from lists.

This list is by no means comprehensive, and you can look up Python documentation or various cheat sheet pages on the web to get more information.

Methods and Objects

Remember how in JavaScript most things are objects? Even, for example, functions? The only exception in JavaScript is the primitives, like numbers or strings.

Well, in Python, everything is an object, including primitives.

This means that integers, strings, booleans, and other primitives also have methods and attributes attached to them:

1
2
3
4
5
6
7
8
  # String methods
  s = "   hello world   "
  print(s.strip())  # "hello world"
  print(s.upper())  # "   HELLO WORLD   "

  # Integer methods
  n = 123
  print(n.bit_length())  # Number of bits needed to represent 123 in binary

And you can use the help function to learn what kind of methods and attributes each primitive provides:

1
2
3
4
  help(str)
  help(int)
  help(bool)
  # ...etc

Packages and Modules

Just like in JavaScript, in Python there are packages and modules:

  • Module - a single file containing Python code
  • Package - a directory containing multiple Python modules

You can import other modules and packages into your code by using the import syntax at the top of your Python file like so:

1
  import numpy as np

To import packages, you first provide the actual name of the package (numpy) followed by the custom abbreviation you would like to assign to it (np). From that point on, you can reference the numpy package in your code using np.

One of the main appeals of Python is its rich ecosystem of third-party packages developed by other people. The typical place to search and install third-party packages is PyPI (Python Package Index). To install packages from PyPI, you can use the pip command-line tool and package installer.

Conclusion

And that’s a wrap for this post. This introduction to Python from a JavaScript developer’s perspective serves as a solid starting point. The next steps would be to explore topics like classes, concurrency, and more.

If you’d like to get more web development, React and TypeScript tips consider following me on Twitter, where I share things as I learn them.

Happy coding!

Share on

Software Development Tutorials
WRITTEN BY
Iskander Samatov
The best up-to-date tutorials on React, JavaScript and web development.