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:
|
|
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:
|
|
- You can use the built-in function
type
to derive the type of the variable.
|
|
- Unlike JavaScript, you cannot simply concatenate strings and numbers in Python. Concatenating strings with other primitive types requires wrapping them with a
str()
function:
|
|
Lists
Basics
Lists in Python are the equivalents of arrays in JavaScript. Same as JavaScript arrays, Python lists allow storing elements with different types:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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 ;
:
|
|
Loops and Iterations
The while
loop is the first loop we’ll take a look at:
|
|
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:
|
|
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:
|
|
Error handling
Error handling in Python is managed with the try
, except
, and finally
statements. Here’s the basic syntax:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
And you can use the help
function to learn what kind of methods and attributes each primitive provides:
|
|
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:
|
|
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!