This tutorial is part of the skills labs within Interactive Data Science and Visualization.

Python Introduction

Hello! This page is intended for those who maybe have less prior experience with Python. This will provide an overview of some common features of the language that may be useful during the semester. That said, this certainly isn't comprehensive. Depending on your comfort level, I may also suggest A Byte of Python as a more complete guide. If you already know Python, you may also consider skipping to Tutorial 2.
Contents

Getting set up for Python

This course can be completed entirely within a web browser and you can use Jupyter Lite to complete this tutorial. While I have written this document assuming you are taking this approach, you may optionally install Python "locally" on your machine instead using the instructions for Linux, Mac, and Windows found in the Hitchiker's Guide to Python.

If you are using Jupyter Lite (or local Jupyter), go ahead and create a new notebook. You can execute code by typing it into a cell and pressing shift-enter (or shift-return). You can also re-execute prior code by clicking on a cell and presing shift-enter (or shift-return).

Exercise

In this exercise, we will write code which tracks bank accounts and moves money between them. This might be a little business-y though that's what computers are often used for! Of course, we will get some variety in the subsequent tutorial where we will move into some more creative coding.

Anyway, a computer program is kind of like an empty world you can fill with your thoughts. You can build almost anything from scratch. However, there are a few basic tools for you to use. For example, computers do know about numbers and math. We will explore developing a useful program taking advantage of the types of things that the computer already knows about, largely by giving names to numbers and telling the computer how to change those values over time.

Arithmetic

Doing arithmetic is easy. We can add numbers (try this out in your notebook):
5 + 4
We can subtract numbers:
5 - 4
We can multiply numbers:
5 * 4
We can divide numbers:
5 / 4
We can make equations:
5 + 2 / 4
We can use parantheses:
(5 + 2) / 4
Every time you use a calculator, you are doing a little programming. Learn more about math in Python.

Variables

We can give names to numbers and change the value of those names over time. We call these names "variables" to annoy mathematicians. For example, we can put $5 in a bank account:
my_bank_account = 5
Now, the concept "my_bank_account" exists within this empty world. We can change that balance:
my_bank_account = my_bank_account + 4
Of course, we can check the value of a variable too by putting it into a cell and executing:
my_bank_account
You can use just about any name you want containing numbers, letters, and underscores. That said, the computer thinks names are case sensitive and, for some old reasons, they can't start with a number. More info about variables.

Lists

Maybe we have more than one bank account. We can create lists of values like a bank account with $5 and another with $10 and another with $15:
my_bank_accounts = [5, 10, 15]
We can refer to individual numbers within the list. For reasons that make more sense to the computer than the humans, the first item in a list is called 0, the second called 1, and so on.
my_bank_accounts[0]
We can use these values like variables. Maybe we can figure out how much is in our first two accounts:
my_bank_accounts[0] + my_bank_accounts[1]
We can even use other variables to figure out which value we want:
index = 0
my_bank_accounts[index]
Of course, we can add to our lists too:
my_bank_accounts.append(20)
my_bank_accounts
See more info about lists. All that said, working on just one value in a list a time can be a pain. So, we will next tell the computer to do something over and over again.

Loops

We can tell the computer to do something multiple time. For example, we can get the total amount across all of our accounts no matter how many accounts we have:
total_money = 0
for bank_account in my_bank_accounts:
    total_money = total_money + bank_account
In the above snippet, we have a "loop" where the indented code below is repeated, once for each bank account in my_bank_accounts. A variable called bank_account exists but only within that indented section. The indent tells the computer to make a small world inside our world (a "room" maybe?) that lasts just for a little while in order to perform some task. After the task is over (in this case, a single bank account is processed), that little world is discarded. There are lots of things you can do with loops, see more info about loops.

Strings

The computer also knows about letters. That said, instead of letters, programmers say "characters" to encompass anything you can type. We can combine these characters together into "strings" which are like numbers in that the computer can manipulate them:

my_name = 'Sam'
They can be read just like numbers given names:
my_name
We can also add strings together:
my_name = my_name + ' Pottinger'
There's lots that strings can do. More info about strings.

Dictionaries

Sometimes it isn't convienent to refer to our first bank account as 0 and our second as 1. Maybe we have different bank accounts for different people. Dictionaries map from one value to another:
bank_accounts = {'mine': 5, 'yours': 10}
Now, instead of using a number as a name within a list, we can use a name as a name:
bank_accounts['mine']
The name we give to a value is called the key:
all_names = ''
for account_name in bank_accounts.keys():
    name_with_space = account_name + ' '
    all_names = all_names + name_with_space
So, we can take a look at all the names:
all_names
We can also look at all the values. Maybe this dictionary has account balances for all the accounts at the bank:
total_money = 0
for balance in bank_accounts.values():
    total_money = total_money + balance
These are just names though and we can add new ones easily.
bank_accounts['someone else'] = 15
Learn more about dictionaries.

Functions

We have given names to numbers but we can also give names to code. For example, you could pay me:
def pay_me():
    bank_accounts['mine'] = bank_accounts['mine'] + 1
    bank_accounts['yours'] = bank_accounts['yours'] - 1
Now, the action "pay_me" exists in this world. You can run that code by using its name and adding parantheses afterwards:
pay_me()
Try seeing what your bank balance is now:
bank_accounts['yours']
Notice the indent. This "function" makes a small world inside our world (a "room" perhaps?) and does some actions there just like we saw with the for loop. We can tell the computer a bit more information about how we want to execute an action:
def transfer(from_account, to_account, amount):
    bank_accounts[from_account] = bank_accounts[from_account] - amount
    bank_accounts[to_account] = bank_accounts[to_account] - amount
These names like "from_account" only exist within that small world inside a world made. They are re-made each time you run "transfer" like so:
transfer("mine", "yours", 2)
transfer("yours", "mine", 3)
Now, let's see what my balance is:
bank_accounts['mine']
Giving names to code can be really useful. Learn more about functions.

Conditionals

Let's say that the bank gives you 1% interest if you have over $2. We can make a function, telling the computer only to do something if something else is true.
def pay_interest(name):
    amount = bank_accounts[name]

    if amount > 2:
        interest = amount * 0.01
    else:
        interest = 0

    new_amount = amount + interest
    bank_accounts[name] = new_amount
We can describe conditions like greater than (>), greater than or equal to (>=), less than (<), less than or equal to (<=), not equal (!=), and equal (==). Let's give it a shot:
pay_interest('yours')
bank_accounts['yours']
We can string together conditions with words like "or" such that only one of two things needs to be true or "and" where both need to be true. Let's say that interest goes up to 2% if someone has over $100:
def pay_interest(name):
    amount = bank_accounts[name]

    if amount > 2 and amount < 100:
        interest = amount * 0.01
    elif amount >= 100:
        interest = amount * 0.02
    else:
        interest = 0

    new_amount = amount + interest
    bank_accounts[name] = new_amount
Note that "if" means do something if something else is true. Meanwhile, "elif" stands for "else if" and means if the first condtion wasn't true, try another one. Finally, else means that, if none of the conditions I tried are true, do something as a fallback. Learn more about conditionals.

Combining ideas

With all of these ideas in place, let's tell the computer about two more actions. First, let's tell the computer how to pay interest to everyone.
def pay_interest_to_everyone():
    for name in bank_accounts.keys():
        pay_interest(name)
Let's give it a shot:
pay_interest_to_everyone()
Also, let's tell the computer how to get the total across all bank accounts in the bank:
def get_total_in_bank():
    total_amount = 0
    for balance in bank_accounts.values():
        total_amount = total_amount + balance
    return balance
That final return statement is new. This tells the computer that, when this action is taken, it creates a number that is left behind after the function finishes (as that small world within a world is destroyed). Give it a shot:
get_total_in_bank()
We can give a name to that result just like we can other numbers:
total_in_bank = get_total_in_bank()
Try reading it like you would any other variable:
total_in_bank
In other words, return can be used to leave behind a bit of work that a function did so it can be used in other code later.

Conclusion

In this session, we told the computer the names of different numbers and text (variables) before we told the computer how to change those values over time. We made lists of values, we made dictionaries, and we told the computer how to take actions it didn't know about before (functions). Finally, we told the computer how to do something in repetition (loops) and only sometimes if certain things are true (conditionals). So far, we've stuck to building these digital worlds out of the types of things that the computer knew about ahead of time like numbers. We also were confined to just text. In the next tutorial, we will enter the world of graphics. You may also return to the skills labs index.

Citations