Jupyter and Python Basics

This notebook was developed by Mike Smith, UCF Computer Science graduate and supporter of K12 teachers and students.

Python

Python is a programming language that is ideal for beginners and useful in data science. But what is a program? A program is simply a set of instructions, called code, written in a language (in this case, Python), usually with some goal in mind. Programming languages are more stringent than everyday languages. In English we can say "the dog chased the ball" or "the ball is being chased by the dog" or "the dog went after the ball" which all mean the same thing. In a language such as Python, there is typically only one way to write a command and the interpreter (which takes the commands and executes them) will be confused and let you know if you've made an error in syntax.

Jupyter

Jupyter lets you create documents, called notebooks, where you can have formatted text (and much more) as well as computer programs all in one document. You can then execute the code from within the notebook.

The non-program parts of the notebook can be formatted using a language called Markdown which is similar to html. Notebooks consist of individual sections called cells which are typically written in either Markdown or code. The text you are reading is contained in a cell, and if you double click it you will see it surrounded with a border and become editable.

Type something here:

Now hit "shift" and "enter" at the same time to let Jupyter know you are done with this section. Jupyter will format it if there are any Markdown tags and move to the next cell.

If you have a "code" cell selected when you hit "shift enter", the code in that cell will execute. Now, before we start, in the menu at the top go to Kernel-->Restart & Clear Output and click. When the dialogue box pops up, click "restart and clear all outputs". This will let you execute one cell at a time as we move through this introduction.

Using Python Within a Jupyter Notebook

Let's try some Python. In programming, the "Hello World" program is usually the starting point. But since in physics the world is not enough, we'll make a slight change.

Remember, click on the code cell to highlight it, then hit "shift enter" to execute the code and move to the next cell.


In [1]:
print("Hello universe!") #the output will show up below this line


Hello universe!

If you did everything correctly, the words "Hello universe!" should have showed up directly above this text. If not, re-read the last section and try it again.

Okay, so what did we do with that line of code? Looking at it closely, there seems to be a lot going on. We have the word print, some parentheses, quotation marks, and a note at the end preceded by a "#".

The word print is a function name in Python. A function is a section of code with a specific name (in this case, print) that is designed to perform some sort of "function".

Some functions require some information (called "arguments") before they work. Arguments are placed between parentheses directly after the function name, no spaces. In this case, the argument we are giving to the print function is "Hello universe!". So this function is designed to print the argument onto the screen. The quotation marks tell it to print exactly what is between them.

The # after the command tells the interpreter to ignore anything on this line that follows it. This is useful when writing code as it allows you to write comments in plain English that help you and others to understand exactly what the code is doing.

Okay, now you give it a try. Single click on this cell (section of formatted text) if you haven't already. It should now have a colored border around it. Now on the Jupyter menu above, click insert-->insert cell below. You should see a new empty cell and the default cell type for new cells is "code". (You can change the cell type with the dropdown box below the menu). Now type the print function to print something you choose.

If you did that correctly and remembered to hit "shift enter" to execute the code, you should have seen your text print. Congratulations, you've written your first section of code! If something didn't work right, review the syntax of your code for typos such as a missing parenthesis, quotation mark, or space.

Variables

Variables are placeholders for data. Python allows us to declare a variable name and give it a value in a single line:


In [2]:
x = 2
print(x) #what would happen if instead we typed print("x")?


2

The number 2 was placed into the variable x. We verified this by printing x.

The variable name x isn't very informative except in very specific cases. Using words as variable names will help with the readability of the code. In the following example, we'll also do some arithmetic manipulation with variables.


In [3]:
length = 10
width = 5
area = length * width
perimeter = 2 * length + 2 * width

print("The area of the rectangle is")
print(area)
print("The perimeter of the rectangle is")
print(perimeter)


The area of the rectangle is
50
The perimeter of the rectangle is
30

Notice that each print statement prints on a new line.

Okay, we've gotten intimate with the print function and sending arguments to it. Let's create our own functions for area and perimeter.

Create Your Own Function


In [4]:
def area_rectangle(length, width):
    area = length * width
    return area

def perimeter_rectangle(length, width):
    perimeter = 2 * length + 2 * width
    return perimeter

print(area_rectangle(8, 4))
print(perimeter_rectangle(8, 4))


32
24

Looking over those functions, we've got some new terms and symbols as well as specific formatting. Since both functions are almost identical, we'll break down the first one:

  • The keyword def tells the interpretor that we are defining a new function.
  • area_rectangle is the name we chose for our function.
  • Directly after our function name is the familiar set of parentheses with names we chose for our arguments, length and width.
  • A colon at the end of our function definition line tells the interpretor that the function starts next. The rest of the function is indented 4 spaces.
  • We then create the variable area and define it in terms of the supplied arguments, length and width.
  • The keyword return ends the function and in this case sends the value stored in area that we calculated. To use the function, we simply call it by name while supplying arguments for length and width. Since we called on our function from within the built-in function print you'll see two sets of embedded parentheses.

Now you give it a try. By following the format of the above code, write a function called square that takes one argument and returns the square of the argument. Remember, you will have to use the menu to create a new cell to type your code into.

Libraries and the Dot Operator

The best thing about functions is that we can make them once and then call on them as many times as we'd like. We wrote useful functions for figuring the area and perimeter of a rectangle, and then you wrote a function that gives you the square of a number.

Multiple functions can be grouped together and saved as a file called a library that we can call on later from whatever program we are writing. For example, it might be useful to take the square function you wrote and write some more functions such as sin, cos and square_root and save them in a library file called math_i_need.

Fortunately, someone has already done this for us and created a library called math that contains many useful functions and constants that we can use in our programs. To tell the interpretor that we would like to use the math library, we use the keyword import.


In [5]:
import math

To use a function or constant from the math library we use the dot operator in between the library name and the function or constant we wish to use:


In [6]:
print(math.pi)


3.141592653589793

In [7]:
print(math.sqrt(9))


3.0

Looping

A useful tool in programming is looping. This allows us to accomplish a task that must be done multiple times with less code. Python provides the for loop as one way to accomplish this:


In [8]:
print("Hello!")

for i in range(5):
    print("Hello again!")
    
print("Okay, I'll be quiet now.")


Hello!
Hello again!
Hello again!
Hello again!
Hello again!
Hello again!
Okay, I'll be quiet now.

The variable i is named by us. It is typical to use i as it stands for "iterator" but the name is arbitrary. Notice the familiar colon and indention pattern to show the statements that are to be executed inside the loop. Any number of statements can be included.

Now lets iterate over an existing set of data. First, we'll create a variable. But instead of this variable being a placeholder for one piece of data, it'll hold a list of information. We'll use the length of the list as our range for the loop:


In [9]:
word_list=["high", "energy", "proton", "collision"]

for i in range(len(word_list)):
    print(word_list[i])


high
energy
proton
collision

Here we defined a list of words as word_list. Each of these words is automatically assigned an index with the first word "high" being at index 0. We also tried something new in the way we defined our range.

In the previous example, we defined our range to be 5 with range(5). In this example, we used range(len(word_list)). What we have is a function within a function. Layered functions are evaluated from the inside out, so len() is evaluated before range. len() is a function that takes a list as an argument and returns the length of the list. In this case, len(word_list) evaluates to 4. So we then are left with range(4) which looks more familiar.

Better yet, Python gives us a shortcut to iterate over lists of data:


In [10]:
for single_word in word_list:
    print(single_word)


high
energy
proton
collision

Congratulations! You've learned enough Python to create some fairly sophisticated programs. Python is a popular programming language, so if you decide you'd like to learn more there are numerous references available online.


In [ ]: