Below we are going to run some code that "imports" packages. This find existing software and loads it into our environment. Packages are amazing because they can help us avoid re-inventing the wheel but taking advantage of code others have written.
The code is just a small chunk called a "cell". In Jupyter, we can run code cell-by-cell, inspecting the outputs as we go! Not all cells have code, for example this one is just text. Check out this section in the SDS4SG textbook to learn more about Markdown in Jupyter.
To run the cell, click on it and click the "Play" button (the triangle between the clipboard and the square) or simply press Ctrl+Enter on your keyboard.
import os
import time
The landing page for JupyterLab looks like this:
We skipped this landing page by opening a notebook directly, but you can always access this screen by clicking the blue "+" button in the top-left. This allows you to open new notebooks with various kernels (Python environments with pre-installed packages), launch a console with different software environments and if you scroll down:
You can also open the terminal or create other types of files.
At the very top of the screen, you can view various menus:
The File Menu The File menu can be used for basic operations such as opening and closing tabs, saving work, reloading, and downloading and exporting content. Additionally, the Jupyter Control Panel can be accessed from this menu (File -> Hub Control Panel) to stop and restart your Jupyter server.
The Edit Menu The Edit menu allows for edit operations within the current cell. You can add, delete, edit, select, copy, move, and merge/split code and display cells. You can also search content or jump to a line within this menu.
The View Menu The View menu controls how content within JupiterLab is displayed. With this menu, you can show and hide menus and panels and change how cell content is viewed.
The Run Menu The Run menu is used to run Jupyter Notebook cells within a tab. The Restart Kernel and Run All command is commonly used when a notebook requires custom installs to run.
The Kernel Menu The Kernel menu is used to stop, restart, shut down, and change kernels.
The Tabs Menu One of the key features of the JupyterLab interface is the ability to have multiple tabs open at once. You can have multiple notebooks, terminal sessions, and other files open at the same time, and can easily toggle between them by clicking on the tab name at the top of the editing window. From the Tabs dropdown menu, you can switch between tabs, see the keyboard shortcuts to switch between tabs, and see a list of the tabs you currently have open.
The Settings Menu The JupyterLab interface may be customizable. For example, you can switch JupyterLab into dark mode by clicking Settings -> JupyterLab Theme:
From the Settings menu, you can also change your font size, customize the text editor settings, and turn autosave on and off.
The left sidebar has a variety of components, including the File Browser:
You can also use the "Running Content Pane" to see your open terminals, windows, and kernels:
Right below the name of the notebook is a menu you can use for running and editing notebooks:
The "Run" button (Play/Triangle) executes a cell, but you can also use CTRL+Enter or Shift+Enter when selected on a cell. Try that below:
print("Hello world!")
The "Interrupt the Kernel" button (Stop/Square) interupts any code running in the notebook. Run the cell below (which will loop forever) and then stop it:
while True:
time.sleep(1) # note the tab/indent. This means everything indented will fall under this "while" loop.
You should see a "KeyboardInterrupt" error, this is expected when using the Stop button. When in doubt the interrupt button is a great first place to go if you're not sure what the code is doing. Another option is Kernel->Restart. This will stop the code that is running, "forget" all of the code you ran before, and allow you start running the code all over again. The actual code and contents of the notebook will be unaffected though!
Note that you can also change the type of cell between Markdown (static text you're reading) and Code (runnable cells).
Select the cell below, change the type to Code, and run it:
lower = 0 upper = 100
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num)
A few other useful options exist in the Run menu:
Run All Above Selected Cell Run Selected Cell and All Below...and in the Kernel menu:
Restart Kernel and Clear OutputsRestart Kernel and Run All CellsWe will assume you have no experience with Python, so here is a VERY quick crash course!
Generally, there are two categories of things in coding: (1) objects that store data and (2) functions that manipulate data. For example, a number would be an object and an operation like + would be a function.
int for integer. These types are useful for identifying when something has gone wrong. For example, 4+'4' might give a weird result, until you see that 4 is an int (integer) and '4' is a str (a "string" of letters aka text).We can use the built-in type function to determine something's type. You generally call a function by using the function's name (e.g., type) and then passing in arguments within parentheses. They are the data you are calling the function on. For example, type(4) is calling the type function on the number 4. A few examples are below:
type(4)
type('4')
type(round)
You can create and store data as variables. You do this by naming the variable (using numbers, letters, and underscores usually, definitely no spaces) and saying it is equal to something else. Not all variable names are available (for example, special words like list or type can't be used because Python has its own uses for those), but an example is below:
addition_result = 2 + 4
The code below declares a variable addition_result and stores the result of 2+4 in it. We can view the contents of a variable in Jupyter by running a cell with just that variable name, or my generally by calling the print function on it:
addition_result
print(addition_result)
Below, we are going to declare a function. This is done by saying def (short for define), giving the function a name, and declaring the arguments (the variables you expect to be passed in).
We will create a very basic function called add_two. The function will take a number (saved as number) and return (give back) that number plus two. I've created the basics of the function below, please finish the function and then test it out!
Note that you need to re-run the cell below for every change you make. The computer doesn't know about a variable or function unless you run it!
def add_two(number): # this is the basics, please finish my function I got tired! Don't forget to
# note the tab/indent. This means everything indented will fall under this function.
number = number # what might I put here to add two?
return number # you can leave this line as it is: it just returns (gives back) the value stored in the variable
# in this cell, write the necessary code to call the add_two function and pass in any number as an argument!
This is a big topic, so we won't go too in-depth here, but programming is amazing because you don't need to specify everything you want to happen one-by-one! You can use tools like if...else and for ... in ... to complete repetitive or complex tasks.
For example, imagine we have a list of integers from 1 to 20 and we want to print either "even" or "odd" for each number. Writing print(even) and print(odd) would be annoying 10 times each and the code would break if I asked you do the same thing for numbers 2 to 21! Instead, we can write code that adapts to our needs.
lists and for¶list - a list holds a bunch of data in order. You can create lists using brackets and putting the contents in between them with commas separating them. For example, [1, 2, 3]. Wmy_list = [1, 2, 3] # declare a variable `my_list` and save the result
print(my_list) # print the variable
We can also refer to each object within a list starting with the zeroth (we start counting from zero in programming) item. To do this, use brackets after the list and put the "index" you want to refer to (e.g., the item number).
my_list[1] # this will print the "1st" item (starting from zero so really the second one)
A cool thing with lists is that we can iterate through them. This means going through the list one-by-one. These are called "for loops" because loop through the list for each item.
There are a few ways to do this, let's see below:
for num in my_list: # this means for each thing in my_list save it temporarily as `num` and do something with it
# note the tab/indent. This means everything indented will fall under this "for" loop.
print(num) # this just print each item
for i in range(len(my_list)): # this uses the order of the list to go refer to the list. Starting at zero and going to the end.
print(my_list[i]) # the bracket at the end of the list means "index" so we are referring to index i
The above version of the for loop combines two cool tricks: len which gives the length of an object and range which creates a list from 0 to n-1 (where n is the number passed in). So basically the code does something like: range(len(my_list)->range(3)->[0,1,2].
if, elif and else¶We can use these statements to check if something is true (or false) and have our code react to that.
if - the if statement checks if something is true and if so, does the code indented beneath it.my_name = "Alex" # create a variable my_name
if my_name == "Alex": # check if the variable `my_name` is equal to (==, two equal signs checks for equality) "Alex"
print("Access granted") # if the above is true, print "Acess granted"
In the above line of code, change the my_name variable to your name run the code. Unless your name is "Alex" you shouldn't get a result!
elif - if the if statement above an elif is not true, it will check the elif (short for else if) statements to see if they are true.We can demonstrate this with a quick change to our "name checking software":
my_name = "Ronald" # create a variable my_name
if my_name == "Alex": # check if the variable `my_name` is equal to (==, two equal signs checks for equality) "Alex"
print("Access granted") # if the above is true, print "Acess granted"
elif len(my_name) < 10: # check if `my_name` has less than 10 letters
print("your name is less than 10 letters")
else - if none of the above if and elifs are true, we do this!One more change:
my_name = "AlexanderMichels" # create a variable my_name
if my_name == "Alex": # check if the variable `my_name` is equal to (==, two equal signs checks for equality) "Alex"
print("Access granted") # if the above is true, print "Acess granted"
elif len(my_name) < 10: # check if `my_name` has less than 10 letters
print("your name is less than 10 letters")
else: # if neither of the two are true
print("you name is 10 or more letters")
Note that having a new if will create a new if statement. For example, if you check if a number is zero and if it is even using if statements (as opposed to if and elif) you could get true for both.
my_number = 0
if my_number == 0:
print("it's zero")
if my_number % 2 == 0: # checks if the number is evently divisible by zero
print("it's even")
If¶Now we can combine both of these ideas to make some code that will even or odd for each number in a list with the code below:
one_to_twenty = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
for num in one_to_twenty: # for each item in the list
if num % 2 == 0: # if it is evenly divisible by 2
print(num, "is even") # here we are printing both the num variable and the string " is even"
else:
print(num, "is odd") # here we are printing both the num variable and the string "is odd"
Here are a few exercises to test your knowledge of Python. You do not necessarily have to complete all of them and I recommend attempting the coding portion of problems without using external tools (e.g., internet), but you can use the internet if necessary. The goal of these problems is to help you practice and learn though, not to see if Google or ChatGPT still works.
round function and select "Show Contextual Help." You may have to click on the function name again and/or wait a second to see the result pop-up. This is a great first option when you get stuck!import math
round(1.1)