Jovian
⭐️
Sign In

First Steps with Python and Jupyter notebooks

Part 1 of "A Gentle Introduction to Programming with Python"

This tutorial is the first in a series on introduction to programming using the Python language. These tutorials take a practical coding-based approach, and the best way to learn the material is to execute the code and experiment with the examples. Check out the full series here:

  1. First Steps with Python and Jupyter notebooks
  2. A Quick Tour of Variables and Data Types in Python
  3. Branching in Python using Conditional Statements and Loops
  4. Writing Reusable Code Using Functions in Python
  5. Reading and Writing Files in Python
  6. Object Oriented Programming with Classes in Python

How to run the code

This tutorial hosted on Jovian.ml, a platform for sharing data science projects online. You can "run" this tutorial and experiment with the code examples in a couple of ways: using free online resources (recommended) or on your own computer.

This tutorial is a Jupyter notebook - a document made of "cells", which can contain explanations in text or code written in Python. Code cells can be executed and their outputs e.g. numbers, messages, graphs, tables, files etc. can be viewed within the notebook, which makes it a really powerful platform for experimentation and analysis. Don't afraid to experiment with the code & break things - you'll learn a lot by encoutering and fixing errors. You can use the "Kernel > Restart & Clear Output" menu option to clear all outputs and start again from the top of the notebook.

Option 1: Running using free online resources (1-click, recommended)

The easiest way to start executing this notebook is to click the "Run" button at the top of this page, and select "Run on Binder". This will run the notebook on mybinder.org, a free online service for running Jupyter notebooks. You can also select "Run on Colab" or "Run on Kaggle", but you'll need to create an account on Google Colab or Kaggle to use these platforms.

Option 2: Running on your computer locally

You'll need to install Python and download this notebook on your computer to run in locally. We recommend using the Conda distribution of Python. Here's what you need to do to get started:

  1. Install Conda by following these instructions. Make sure to add Conda binaries to your system PATH to be able to run the conda command line tool from your Mac/Linux terminal or Windows command prompt.

  2. Create and activate a Conda virtual environment called zerotopandas which you can use for this tutorial series:

conda create -n intro-to-python -y python=3.8 
conda activate intro-to-python

You'll need to create the environment only once, but you'll have to activate it every time want to run the notebook. When the environment is activated, you should be able to see a prefix (intro-to-python) within your terminal or command prompt.

  1. Install the required Python libraries within the environmebt by the running the following command on your terminal or command prompt:
pip install jovian jupyter numpy pandas matplotlib seaborn --upgrade
  1. Download the notebook for this tutorial using the jovian clone command:
jovian clone aakashns/first-steps-with-python

The notebook is downloaded to the directory first-steps-with-python.

  1. Enter the project directory and start the Jupyter notebook:
cd first-steps-with-python
jupyter notebook
  1. You can now access Jupyter's web interface by clicking the link that shows up on the terminal or by visiting http://localhost:8888 on your browser. Click on the notebook first-steps-with-python.ipynb to open it and run the code. If you want to type out the code yourself, you can also create a new notebook using the "New" button.

Performing arithmetic using Python

Let's begin by using Python as a calculator. You can write and execute Python using a code cell within Jupyter.

To create a new cell within Jupyter, you can select "Insert > Insert Cell Below" from the menu bar or just press the "+" button on the toolbar. You can also use the keyboard shortcut Esc+B to create a new cell. Once a cell is created, click on it to select it. You can then change the cell type to code or markdown (text) using "Cell > Cell Type" menu option. You can also use the keyboard shortcuts Esc+Y and Esc+M. Double click a cell to edit the content within the cell. To apply your changes and run a cell, use the "Cell > Run Cells" menu option or click the "Run" button on the toolbar or just use the keyboard shortcut Shift+Enter.

Edit the code cells below, and run them to perform the calculation and view the result. Can you guess what the //, % and ** operators are used for?

In [1]:
2 + 3 + 9
Out[1]:
14
In [2]:
99 - 73
Out[2]:
26
In [3]:
23.54 * -1432
Out[3]:
-33709.28
In [4]:
100 / 7
Out[4]:
14.285714285714286
In [7]:
100 // 7
Out[7]:
14
In [8]:
100 % 7
Out[8]:
2
In [9]:
5 ** 3
Out[9]:
125

As you might expect, certain operators like / and * take precendence over other operators like + and - as per mathematical conventions. You can use parantheses i.e. ( and ) to specify the order in which operations are performed.

In [10]:
((2 + 5) * (17 - 3)) / (4 ** 3)
Out[10]:
1.53125

Python supports the following arithmetic operators:

Operator Purpose Example Result
+ Addition 2 + 3 5
- Subtraction 3 - 2 1
* Multiplication 8 * 12 96
/ Division 100 / 7 14.28..
// Floor Division 100 // 7 14
% Modulus/Remainder 100 % 7 2
** Exponent 5 ** 3 125

Solving multi-step problems using variables

Let's try solving a word problem using Python:

A grocery store sells a bag of ice for $1.25, and makes 20% profit. If it sells 500 bags of ice, how much total profit does it make?

We can list out the information provided, and gradually convert the word problem into a mathematical expression which can be evaluated using Python.

Cost of ice bag ($) = 1.25

Profit margin = 20% = .2

Profit per bag ($) = profit margin * cost of ice bag = .2 * 1.25

No. of bags = 500

Total profit = no. of bags * profit per bag = 500 * (.2 * 1.25)

In [11]:
500 * (.2 * 1.25)
Out[11]:
125.0

Thus, the grocery store makes a total profit of $125.0 . While this is a reasonable way to solve a problem, it's not quite clear by looking at the code what the numbers represent. We can give names to each of the numbers by creating Python variables.

Variables: While working with a programming language such as Python, informations is stored in variables. You can think of variables are containers for storing data. The data stored within a variable is called it's value.

In [12]:
cost_of_ice_bag = 1.25
In [13]:
profit_margin = .2
In [14]:
number_of_bags = 500

The variables cost_of_ice_bag, profit_margin and number_of_bags now contain the information provided in the word problem. We can check the value of a variable by typing its name into a cell, and we can combine variables using arithmetic operations to create other variables.

Tip: While typing the name of an existing variable in a code cell within Jupyter, you can type the first few characters and press the Tab key to autocomplete the variable's name. Try typing pro in a code cell below and press Tab to autocomplete to profit_margin.

In [15]:
profit_margin
Out[15]:
0.2
In [16]:
profit_per_bag = cost_of_ice_bag * profit_margin
In [17]:
profit_per_bag
Out[17]:
0.25
In [18]:
total_profit = number_of_bags * profit_per_bag
In [19]:
total_profit
Out[19]:
125.0

Storing and manipulating data using appropriately named variables is a great way to explain what your code does.

Let's display the result of the word problem using a friendly message. We can do this using the print function.

Functions: A function is a reusable set of instructions. A function takes one or more inputs, performs certain operations, and often returns an output. Python provides many in-built functions like print, and also allows us to define our own functions.

In [20]:
print("The grocery store makes a total profit of $", total_profit)
The grocery store makes a total profit of $ 125.0

print: The print function is used to display information. It takes one or more inputs which can be text (within quotes e.g. "this is some text"), numbers, variables, mathematical expressions etc. We'll learn more about variables & functions in the next section.

Creating a code cell for each variable or mathematical operation can get tedious. Fortunately, Jupyter allows you write multiple lines of code within a single code cell. Let's rewrite the solution to our word problem within a single cell.

In [21]:
# Store input data in variables
cost_of_ice_bag = 1.25
profit_margin = .2
number_of_bags = 500

# Perform the required calculations
profit_per_bag = cost_of_ice_bag * profit_margin
total_profit = number_of_bags * profit_per_bag

# Display the result
print("The grocery store makes a total profit of $", total_profit)
The grocery store makes a total profit of $ 125.0

Note that we're using the # character to add comments within our code.

Comments: Comments and blank lines are ignored during execution, but they are useful for providing information to other humans (including yourself) about what the code does. Comments can be inline (at the end of some code), on a separate line, or even span multiple lines.

Inline and single line comments start with #, whereas multi-line comments begin and end with three quotes i.e """. Here are some examples of code comments:

In [23]:
my_favorite_number = 1 # an inline comment
In [24]:
# This comment gets its own line
my_least_favorite_number = 3
In [25]:
"""This is a multi-line comment.
Write as little or as much as you'd like.

Comments are really helpful for people reading
your code, but try to keep them short & to-the-point.

Also, if you use good variable names, then your code is
often self explanatory, and you may not even need comments!
"""
a_neutral_number = 5

Evaluating conditions using Python

Apart from arithmetic operations, Python also provides several oprations for comparing numbers & variables.

Operator Description
== Check if operands are equal
!= Check if operands are not equal
> Check if left operand is greater than right operand
< Check if left operand is less than right operand
>= Check if left operand is greater than or equal to right operand
<= Check if left operand is less than or equal to right operand

The result of a comparision operation is either True or False (note the uppercase T and F). These are special keywords in Python. Let's try out some experiment with comparision operators.

In [26]:
my_favorite_number = 1
my_least_favorite_number = 5
a_neutral_number = 3
In [28]:
# Equality check - True
my_favorite_number == 1
Out[28]:
True
In [29]:
# Equality check - False
my_favorite_number == my_least_favorite_number
Out[29]:
False
In [30]:
# Not equal check - True
my_favorite_number != a_neutral_number
Out[30]:
True
In [31]:
# Not equal check - False
a_neutral_number != 3
Out[31]:
False
In [32]:
# Greater than check - True
my_least_favorite_number > a_neutral_number
Out[32]:
True
In [33]:
# Greater than check - False
my_favorite_number > my_least_favorite_number
Out[33]:
False
In [34]:
# Less than check - True
my_favorite_number < 10
Out[34]:
True
In [35]:
# Less than check - False
my_least_favorite_number < my_favorite_number
Out[35]:
False
In [36]:
# Greater than or equal check - True
my_favorite_number >= 1
Out[36]:
True
In [37]:
# Greater than or equal check - False
my_favorite_number >= 3
Out[37]:
False
In [38]:
# Less than or equal check - True
3 + 6 <= 9
Out[38]:
True
In [39]:
# Less than or equal check - False
my_favorite_number + a_neutral_number <= 3
Out[39]:
False

Just like arithmetic operations, the result of a comparison opration can also be stored in a variable.

In [41]:
cost_of_ice_bag = 1.25
is_ice_bag_expensive = cost_of_ice_bag >= 10
print("Is the ice bag expensive?", is_ice_bag_expensive)
Is the ice bag expensive? False

Combining conditions with logical operators

The logical operators and, or and not operate upon conditions and True & False values (also known as booleans). and and or operate on two conditions, whereas not operates on a single condition.

The and operator returns True when both the conditions evalute to True. Otherwise it returns False.

a b a and b
True True True
True False False
False True False
False False False
In [42]:
my_favorite_number
Out[42]:
1
In [43]:
my_favorite_number > 0 and my_favorite_number <= 3
Out[43]:
True
In [44]:
my_favorite_number < 0 and my_favorite_number <= 3
Out[44]:
False
In [45]:
my_favorite_number > 0 and my_favorite_number >= 3
Out[45]:
False
In [46]:
True and False
Out[46]:
False
In [47]:
True and True
Out[47]:
True

The or operator returns True if at least one of the conditions evalute to True. It returns False only if both conditions are False.

a b a or b
True True True
True False True
False True True
False False False
In [48]:
a_neutral_number = 3
In [49]:
a_neutral_number == 3 or my_favorite_number < 0
Out[49]:
True
In [50]:
a_neutral_number != 3 or my_favorite_number < 0
Out[50]:
False
In [51]:
my_favorite_number < 0 or True
Out[51]:
True
In [52]:
False or False
Out[52]:
False

The not operator returns False if a condition is True and True if the condition is False.

In [53]:
not a_neutral_number == 3
Out[53]:
False
In [54]:
not my_favorite_number < 0
Out[54]:
True
In [55]:
not False
Out[55]:
True
In [56]:
not True
Out[56]:
False

Logical operators can be combined to form complex conditions. Use round brackets or parantheses ( and ) to indicate the order in which logical operators should be applied.

In [57]:
(2 > 3 and 4 <= 5) or not (my_favorite_number < 0 and True)
Out[57]:
True
In [68]:
not (True and 0 < 1) or (False and True)
Out[68]:
False

If parantheses are not used, logical operators are applied from left to right.

In [69]:
not True and 0 < 1 or False and True
Out[69]:
False

Experiment with arithmetic, conditional and logical operators in Python using the interactive nature of Jupyter notebook. We will learn more about variables and functions in future tutorials.

Save and upload your notebook

Whether you're running this Jupyter notebook on an online service like Binder or on your local machine, it's important to save your work from time, so that you can access it later, or share it online. You can upload this notebook to your Jovian.ml account using the jovian Python library.

First, you need to install the Jovian python library, if it isn't already installed.

In [70]:
!pip install jovian --upgrade --quiet
In [71]:
import jovian
In [ ]:
jovian.commit(project='first-steps-with-python')
[jovian] Attempting to save notebook..
In [ ]: