Introduction to Python

Sanjeev Lingam-Nattamai
Deep Dives with Data
9 min readMay 22, 2020

Python is an interpreted, high-level, object-oriented language that was created by Guido Van Rossum in 1990. As an interpreted language, Python code is analyzed and executed instruction by instruction. Python is one of the few languages where it has been used successfully in large projects that offer great flexibility and ease of use compared to other languages.

Why learn Python?

Python is a great language to learn because it is easy to learn, the syntax structure is simple, and it is widely used in many different fields. For example, here are different fields of work where Python libraries and frameworks are directly used:

  • Web Development (Django, Flask, Pylons frameworks)
  • Data Science and Visualization (Numpy, Pandas, and Matplotlib libraries)
  • Machine Learning (Tensorflow, Scikit-learn libraries)
  • Desktop/Mobile Applications (PyQt, Kivy and many more libraries)

If any of these fields interest you or if you want to pick up a programming language, then Python is a great fit!

Installation

I use Jupyter Notebook from the Anaconda distribution to code in Python. You will be able to download the Anaconda software here. Once the installation of Anaconda has finished, you are now able to start up Jupyter Notebook which is a web application that is pre-downloaded in Anaconda. I found a great resource that goes through how to open up the Jupyter Notebook server and create notebooks here. You’ll be able to find the information you need at the ‘Starting the Jupyter Notebook Server’ portion of the ‘Getting Up and Running with Jupyter Notebook’ section of the tutorial. Once you’re able to create a notebook, you’re ready to start learning Python!

Variables

In programming, variables are essentially words that store values of different data types. The main data types used are:

  • Integers (int): Whole numbers (Examples are: 2, 5, 7)
  • Floats (float): Decimals (Examples are: 0.5, 2.7, -12.0)
  • String (str): A sequence of characters that are enclosed by single or double quotes (Examples are: ‘hello’, “hi”, ‘abc’)
  • Boolean (bool): Takes in two values which are True, False

Here is an example of a variable of each of these data types being created:

A convenience about Python is that a variable is created the instant you assign a value to it. In the example above, the respective variables are assigned to their values and the program knows what data type the variable is when the program is run. Also, you can organize and describe your code by adding comments. In Python, single-line comments begin with a hash mark (#).

Rules for Variable Names

When naming a variable in Python, there are rules that must be followed:

  • Variable names must start with either a letter or an underscore
  • Variable names cannot start with a number
  • Variable names can only contain alphanumeric characters(A-z, 0–9, and _)
  • Variable names are case-sensitive (hello and HELLO are two different variables)

Printing

In order to print out these variables to standard output, you can call the print() function and place whatever you want to print inside the parenthesis like seen in the example below:

You can also call the print() function without anything inside the parenthesis and this will result in a blank line being printed.

Conditional Statements

Conditions

Oftentimes in Python programs, we need to be able to compare variables to each other in certain tasks. To do so, Python has logical operators with these conditions:

  • Equals: x == y
  • Not Equals: x != y
  • Greater than: x > y
  • Greater than or equal to: x >= y
  • Less than: x < y
  • Less than or equal to: x <= y

Ultimately, these comparisons between two variables result in a boolean result (either True or False).

If-Statement

What we have gone through so far is pretty straight-forward and sequential. However, this isn’t the case in the real world where we are constantly tasked with making decisions based on conditions. For example:

  • “I will go outside if the temperature is greater than 65 degrees”
  • “I will eat tacos if it is Tuesday”
  • “I will go for a run if it is Sunday”

This is where if-statements come in. If-statements evaluate the comparison between two values and if the comparison is True, then the statements inside the if-statement execute. This can be shown with this example:

In the previous conditional statement example, since the temperature variable is 75 and is greater than 65, then that statement is true. However, what happens if the if-statement condition was false since nothing would get printed in this situation?

Else-Statement

The else-statement is there so that if the if-statement comparison is false, then the statements inside the else-statement automatically execute. The else-statement acts as a fallback for the if-statement. Here is an example:

In the example, since the temperature is 50 and is not greater than 65, the if-statement comparison is false. This means that the else-statement gets executed. However, what happens if you have more than one condition?

Elif-Statement

The elif-statement can be used if you have more than one condition. It is added sequentially after the if-statement and before the else-statement. You can also have more than one elif-statement if necessary. Here is an example:

The if-elif-else statements are checked sequentially. The if-statement is first checked and if it’s false, we move onto to the elif-statement. If the elif-statement happens to also be false, then the else-statement is executed.

Boolean Operators

Sometimes, there are situations where multiple conditions are needed and so conditional statements need to be combined. This can be done with boolean operators and the main ones used in if-statements are:

  • AND: As an example, if you want to check if two values are both greater than your breakpoint value, then the ‘AND’ operator would be great to use.
  • OR: If you want to check if at least one of your two values is greater than your breakpoint value, then the ‘OR’ operator would be great to use.

Collections

Along with integers, floats, strings, and boolean data types, Python also has container data types which are known as collections. There are four container data types.

Lists

The first container data type is a list. A list is a collection that stores values and is ordered, changeable, and allows duplicate elements. In Python, lists are written with square brackets. Here are examples of lists:

As you can see with myList3 in the example above, lists in Python can also contain multiple data types.

An important functionality of lists is being able to access each element. This is known as indexing and it is done using square bracket notation. Python lists are zero-indexed which means that the first element in a list is index 0, the second element is index 1, the third element is index 2, and so on. Here is an example of indexing:

Along with indexing, there is also negative indexing in Python. So with the last example above, index -1 refers to the last element, index -2 refers to the second to last element, and so on.

However, what if you want to access a portion of your list and not just one element? This can be done with list slicing where you can slice a range of elements off of your original list. The notation of slicing in Python is myList[(index1):(index2)].

Here is an example:

With slicing, there is a colon that separates the two indices. However, in the resulting list, the first index is included, but the second index isn’t. For example, myList[1:3] results in the list [‘b’, ‘c’] because ‘b’ is index 1 and ‘c’ is index 2. Index 3, ‘d’, is not included. If you want to include index 3, then your slicing operation would be myList[1:4].

While indexing lists is great, it is also important to be able to manipulate lists. Python lists have many methods, but here are three really important methods that are essential to know:

  • append() — The append() method appends an element to the end of a list
  • remove() — The remove() method removes an element from the list
  • len() — The len() method gets the number of elements in a list or in other words, the length

Here is an example of these methods:

Along with these methods, there are many more useful Python list methods. If you are interested in taking a look at them, here is a website that has explanations of each method.

Tuples

A tuple is a collection that is ordered and can have duplicate elements. Unlike a list, a tuple is unchangeable meaning that once you create a tuple, it is fixed and you cannot add or remove any element from it. A tuple can contain multiple data types as well. In Python, tuples are written with round brackets or parentheses. Here are examples of tuples:

As you can see from the example, indexing and range of indexing can be done with tuples as well as it is similar to lists.

Sets

A set is a collection that is unordered and it’s not indexable. Unlike lists and tuples, there cannot be duplicate elements in a set. Sets are unordered meaning that when you add to a set, it’s not going to add at the end of the set, rather it’s going to be randomly added. Sets are written with curly braces in Python. Here are three of the more important methods you need to know for sets along with an example:

  • add() — The add() method adds an element to the set
  • remove() — The remove() method removes an element from the set
  • update() — The update() method adds more than one element to the set

A limitation of sets is that it’s not indexable, so you need to iterate through the set which we’ll go through in the next section. However, sets are still useful because you are able to use set operations to compare two sets with each other. If you are interested in taking a look at all of the set operations, you can find it here.

Dictionaries

A dictionary is another type of collection that is unordered and unchangeable, but it can be indexed like a list and a tuple. In Python, dictionaries are written with curly braces and they have keys and values. A dictionary cannot have duplicate keys, but it can have duplicate values. Here is an example of a dictionary:

Overall, these four collection data types are useful and it’s really important to understand each of their properties when deciding which one to use for an application.

Iteration

For Loops

A for loop is a type of loop that is used to iterate through a sequence whether it be a collection data type or a string. Here are some examples of for loops:

In for loops, the two main keywords are ‘for’ and ‘in’

  • for — the for keyword acts as an iterator
  • in — the in keyword is used to actually say what data type variable is getting iterated through

So for the first for loop example above, the ‘i’ acts as a placeholder as it is moving through each element in myList and printing it out one by one on a new line.

For the second example, the answer is the same as the first, but it’s done in a different way. Instead, the range() function is used which returns a sequence of numbers that starts at 0 by default. So, the ‘i’ iterates through range(len(myList)) which is range(5) and range(5) is the sequence of 0, 1, 2, 3, 4. So finally, when the elements are printed, they have to be indexed first.

While Loops

The while loop is a type of loop that executes a set of statements so long as the while condition is true. Here is an example:

One important note is that in this example, the incrementer variable adds one each time inside the while loop. If this wasn’t done, then the while loop would never break and continue forever which is known as an infinite loop. Therefore, it’s always important to check and make sure that your while condition eventually fails and stops running so that infinite loops can be avoided.

Functions

Functions are blocks of code that are run when they are called. They are incredibly useful for organizing your code into separate tasks. Another benefit of functions is that you can pass in data (parameters) that can be used and manipulated inside the function. As a result, functions oftentimes return data back with the return() function at the end of the execution of a function. Here are examples of functions:

Summary

What we learned in Python:

  • Variables
  • Printing
  • Conditional Statements
  • Collection Data Types
  • Iteration
  • Functions

While this is a lot of good material to start with, there are still a lot more topics to cover. If you are interested in learning more and are curious about diving deeper into Python, I recommend visiting this site which covers more topics in Python along with those that we have already covered. Finally, if you are interested in a specific field like data analysis or machine learning and you want to learn how to work with specific Python software libraries that pertain to these fields, this site describes 30 useful Python libraries along with their features.

--

--

Sanjeev Lingam-Nattamai
Deep Dives with Data

SDE @ AWS | Graduate of Computer Science + Statistics @ Purdue University