Table of Contents

Using Python as a calculator

The following are examples of the kinds of Python expressions that we can use.

In [66]:
4 + 5
In [67]:
15 - 12

You can also have expressions whose value isn't a number, but is instead True or False. Note the double "equals" sign. You must use == in this context. A single "equals" sign means something else.

In [68]:
3 == 4
In [69]:
4 == 4

Going beyond just numbers

So far, we have only seen numbers (integers) and boolean values (True and False) as values. Strings (i.e., text) is another possible value. In fact, in Python, we can multiply strings by integers, and add strings.

String in Python are text enclosed in quotes.

In [70]:
"ha" * 10
In [71]:
"ha" + "hah"

Note that you can have any text at all encolsed in quotes:

In [72]:
"the number" + " " + "42"
'the number 42'
In [73]:
"hi" == "hello"
In [74]:
"hello" == "hello"


Variables in programming are used to store values. For example, here is how to store the number 42 in a variable called memory

In [75]:
memory = 42

We can now retrieve the value that we stored in memory by typing memory in the shell

In [76]:

Note that there is nothing special about calling the variable memory: we can equally well have variables called lol or hours_of_sleep. (Variable names cannot have spaces in them, and must start with a letter.)

In [77]:
lol = 101
hours_of_sleep = 2

We computed things like 42 + 5 before. We can also use variables in place of actual numbers:

In [78]:
hours_of_sleep + .15

We can assign values that are computed like to to variables:

In [79]:
with_snooze = hours_of_sleep + .15

What we just did was assign the value hours_of_sleep + .15 (which evaluates to 2 + .15 = 2.15) to a new variable called with_snooze:

In [80]:

So far, what we did was type in the value of a variable in the shell to check what its value is. When we write programs (i.e., series of instructions), we can't (or don't want to) check the values of variables in the shell. Instead, we use Python's print function:

In [81]:
In [82]:
print(with_snooze + .15)
In [83]:

Here is a silly program (copy and paste it into Pyzo, and use Cntrl-E (or Cmd-E on Mac) to run it.)

In [84]:
hours_of_sleep_weekend = 20
print(4 + 5)
print(15 - 12)
5 + 10

Note that when we run a program like that in Pyzo, we only get output when we use print. Python (basically) ignores it when we just type in values into the program (such as "lol", 42, or 15 - 12) but don't ask for them to be printed.

Variables vs. strings

Note that strings are enclosed in quotes, and variables are not. For example, consider this:

In [85]:
a = hello

We got an error! That's since hello is not enclosed in quotes, Python assumes that hello is a variable. But we haven't defined a variable called hello. That why Python gives us an error. There are two things that we could mean here.

First, maybe we meant to put the value "hello" in a, and then print a. Then, what we should have written is:

In [86]:
a = "hello"

Or maybe we wanted to actually put in a the same value that we had in a variable called hello, we just forgot to define the variable hello. We could fix that by defining the variable hello.

In [87]:
hello = "bye"
a = hello

A very simple program + comments

Let's now write a program that creates a variable called hours_of_sleep, and then modifies it, and prints it while it modifies it.

Note that Python ignores anything that comes after the pound sign #. Anything that comes in the line after the # is called a comment. Comments are intended for human readers of the code.

In [88]:
hours_of_sleep = 2
hours_of_sleep = 2.5                    #Curriculum review!
hours_of_sleep = hours_of_sleep + .15    #Snooze button

Saving files using Pyzo and finding them later

In [89]:
from IPython.display import YouTubeVideo

P1: File Systems + Hello Python

Write a program that prints “Hello Python” and some additional text to the screen. Create a folder called workshop1, and save the program to the file in that folder.

In [90]:
print("Hello Python")
print("Oh, I guess you're here too, hi")
Hello Python
Oh, I guess you're here too, hi

Secret number

Now, let's write our first "substantive" program. Here, we are giving the computer instructions about how to transform a "secret" number.

In [91]:
secret_num = 10
temp = secret_num + 8   #evaluate secret + 8, and put the result
                        #in temp
temp = temp * 2         #evaluate temp * 2, and put the results
                        #in temp
temp = temp / 4
answer = temp - secret_num / 2

The math works out in such a way that you get 4.0 no matter what the secret number is:

In [114]:
secret_num = 26
temp = secret_num + 8   #evaluate secret + 8, and put the result
                        #in temp
temp = temp * 2         #evaluate temp * 2, and put the results
                        #in temp
temp = temp / 4
answer = temp - secret_num / 2

Tracing program in Pyzo

To trace a program means to go through it line-by-line and see how the variables change, which lines are executed, and what is printed as the program is executed.

In [115]:
from IPython.display import YouTubeVideo

Printing more than one thing at a time

A note about print: you can print multiple things at once by separating the things you want to print with commas.

In [93]:
print("hi", "there")
hi there
In [94]:
print("hi", 5)
hi 5
In [95]:
print("cs", "for", "medicine")
cs for medicine

By defaulty, the things you seprate in the comma when you use print are separated by spaces when they get printed out. Usually that's fine, but sometimes you want more flexibility. But we already know enough to get that flexibility!

For example, imagine that you don't want a space between the two strings that you are printing. You could use the fact that + concatenates strings together:

In [96]:
print("C4" + "M")

This is in contradistinction to:

In [97]:
print("C4", "M")
C4 M

P2: Variables and strings

Modify to greet you by your names. For example, if your names happen to be Hermione Granger and Harry Potter, the program should print out the following

Hello, Hermione Granger
Hello, Harry Potter

Now, use variables to print the following without entering the same information more than once:

Hello, Hermione Granger and Harry Potter. Your names are Harry Potter and Hermione Granger. Hi there. Your names are still Hermione Granger and Harry Potter.

In [98]:
print("Hello, Hermione")
print("Hello, Harry")

person1 = "Dr. Evil"
person2 = "Dr. Pepper"

print("Hello,", person1, "and", person2 + ". Your names are", person1, "and", person2 + ". Hi there. Your names are still", person1, "and", person2 + ".")
Hello, Hermione
Hello, Harry
Hello, Dr. Evil and Dr. Pepper. Your names are Dr. Evil and Dr. Pepper. Hi there. Your names are still Dr. Evil and Dr. Pepper.

Note that in order to matche the spaces exactly, we had to resort to sometimes using string concatenation (the +). If we wanted to be a little bit clever, we could actually get away with code that's a little bit neates like so:

In [99]:
person1 = "Dr. Evil"
person2 = "Dr. Pepper"

greetees = person1 + " and " + person2
greeting = "Hello, " + greetees + ". Your names are " + greetees + ". Hi there. Your names are still " + greetees + "."
Hello, Dr. Evil and Dr. Pepper. Your names are Dr. Evil and Dr. Pepper. Hi there. Your names are still Dr. Evil and Dr. Pepper.

This is probably nicer than what we had above, since it's more uniform, more readable, and lets us avoid typing in anything more than once.

Computing exponents

You can do math that's more complicated than addition and multiplication. Use the double asterisk for exponentiation. For example

In [100]:

is $5^2$.

In [101]:

is $27^{\frac{1}{3}} = \sqrt[3]{27}$.

P3: Variables

Fridericia's Formula for the corrected QT is $$QTc = \frac{QTInterval}{RR^{\frac{1}{3}}}$$

The R-R interval is measured in seconds, and can be ontained using $60/HR$, where HR is the heart rate. Set the HR and QT variables, and print the corrected QT interval. Trace your code in Pyzo.

In [102]:
HR = 70
QT = 300 #in milliseconds

RR = 60/HR

QTc = QT/(RR**(1/3))

print("Correct QT Interval:", QTc, "milliseconds")
Correct QT Interval: 315.817979882819 milliseconds

If Statements

If statements are useful for doing different things depending on what the values of some variables are

For example, suppose we want to print the absolute value of n. If n >= 0, we should print n, and otherwise we should pring -n

The (simplified) format of the if statement is:


Note that the columns and the tabs before the blocks are mandatory!

If the CONDITION is True, BLOCK1 is executed, and otherwise BLOCK2 is executed.

In out case the condition is $n \geq 0$ (written as n >= 0 in Python).

In [103]:
n = -5
if n >= 0:

Note that only one of the lines with print is ever executed. If n is positive, then only the first print will run:

In [104]:
n = 5
if n >= 0:

Here is a more complicated example (see the video below).

In [105]:
from IPython.display import YouTubeVideo

To summarize, let's say that you can pay 3 shillings or more to dock and register using an assumed name, and between 1 shilling and 3 shillings to dock and register under your own name.

There are three conditions here: either you pay 3 shillings or more, or you pay between 1 and 3 shillings, or you try to pay less than 3 shillings.

Here is how we can set up the checks for those conditions:

First, we'll check if you are paying 3 shillings or more. If you are, then we don't have to check for anything more, and can let you register straight away.

If the first check fails, we'll check if you are paying 1 shilling or more. If you are, we let you register under your own name.

If that check fails as well, we tell you to go away.

Python allows as to do exactly this: check for multiple conditions in turn. We do that using elif statements (short of "else if," but you have to type elif exactly.)

elif <CONDITION2>:
elif <CONDITION3>:

Python will keep checking the conditions in order until one is True, and will execute the corresponding block. If no condition is True, Python will execute the block under else (blockn)

Note: the tabs and columns are all mandatory, and the format has to be exactly right!

In [119]:
shillings = 2
name = "Jack Sparrow"

if shillings >= 3:
    print("Welcome to Port Royal, Mr. Smith") 
elif shillings >= 1:
    print("Welcome to Port Royal, " + name)
    print("Go away!") 
Welcome to Port Royal, Jack Sparrow

Tracing if statements

In [120]:
from IPython.display import YouTubeVideo

P4: If Statements

Not everybody should be greeted by name. Write Python code that greets by name the person whose name is stored in a variable called greetee, except if the person's name is Lord Voldemort, in which case the program should print the message

I’m not talking to you.

In [107]:
greetee = "Dr. Evil"
if greetee == "Lord Voldermort":
    print("Hello", greetee)
    print("I'm not talking to you")
I'm not talking to you

P5: More If Statements

According to Wikipedia, borderline QTc for men is 431ms-450ms and for women it is 451ms-470ms. Set the variable sex to "male" (or "female"), and write a program that uses the variables HR (heartrate), QT (uncorrected QT interval), and sex ("male" or "female") to print out "normal QTc", "borderline QTc", or "abnormal QTc."

In [116]:
HR = 80
QT = 300
sex = "male"

QTc = QT/(RR**(1/3))   #Compute the corrected QT interval

if sex == "female":
    if QTc > 450:
        print("Abnormal QTc")
    elif QTc >= 431:
        print("Borderline QTc")
        print("Normal QTc")
elif sex == "male":
    if QTc > 470:
        print("Abnormal QTc")
    elif QTc >= 451:
        print("Borderline QTc")
        print("Normal QTc")

    print("Enter 'male' or 'female' as the sex")
Normal QTc


We can obtain input from the user by using input().

In a sesnse, input() is like print() in reverse. To print a, we use


To get a from the user, we use

a = input(prompt)

prompt is the text that the user sees before the cursor.

In [111]:
name = input("What is your name? ")
#User types in the name and presses Enter now
print("Hi", name)
What is your name? Michael
Hi Michael

There is one issue: input() always returns a string -- text that we've been enclosing in quotes. Imagine that we have

In [64]:
n = input("Enter a number: ")
#user types in 42, so n is "42"
print(n * 2)    #prints 4242
Enter a number: 42

In order to store a number in n, we need to convert the string to a number. Here is how we can do it:

In [65]:
n = float(input("Enter a number:"))
#user types in 42, so n is 42
print(n * 2)    #prints 82.0
Enter a number:42

P6: An interactive system for telling the user if their QTc is abnormal

Write a program that asks the user for their sex, QT interval, and heartrate, and outputs whether their QTc is normal/borderline/abnormal.

In [124]:
HR = float(input("Enter your heart rate(in Hz): "))
QT = float(input("Enter your QT interval (in ms): "))
sex = input("Enter your sex: ")

QTc = QT/(RR**(1/3))   #Compute the corrected QT interval

if sex == "female":
    if QTc > 450:
        print("Abnormal QTc")
    elif QTc >= 431:
        print("Borderline QTc")
        print("Normal QTc")
elif sex == "male":
    if QTc > 470:
        print("Abnormal QTc")
    elif QTc >= 451:
        print("Borderline QTc")
        print("Normal QTc")

    print("Enter 'male' or 'female' as the sex")
Enter your heart rate(in Hz): 80
Enter your QT interval (in ms): 300
Enter your sex: male
Normal QTc
In [1]:
In [ ]: