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
Out[66]:
9
In [67]:
15 - 12
Out[67]:
3

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
Out[68]:
False
In [69]:
4 == 4
Out[69]:
True

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
Out[70]:
'hahahahahahahahahaha'
In [71]:
"ha" + "hah"
Out[71]:
'hahah'

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

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

Variables

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]:
memory
Out[76]:
42

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
Out[78]:
2.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]:
with_snooze
Out[80]:
2.15

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]:
print(with_snooze)
2.15
In [82]:
print(with_snooze + .15)
2.3
In [83]:
print("hi")
hi

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)
"lol"
print(15 - 12)
hours_of_sleep_weekend
5 + 10
"lol"
print("hi")
9
3
hi

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
print(a)
bye

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"
print(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
print(a)
bye

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
print(hours_of_sleep)
hours_of_sleep = 2.5                    #Curriculum review!
print(hours_of_sleep)
hours_of_sleep = hours_of_sleep + .15    #Snooze button
print(hours_of_sleep)
2
2.5
2.65

Saving files using Pyzo and finding them later

In [89]:
from IPython.display import YouTubeVideo
YouTubeVideo("0FasnsuPbjg")
Out[89]:

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 hello.py 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
print(answer)           
4.0

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
print(answer)           
4.0

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
YouTubeVideo("Mw03-479UYw")
Out[115]:

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")
C4M

This is in contradistinction to:

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

P2: Variables and strings

Modify hello.py 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 + "."
print(greeting)
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]:
5**2
Out[100]:
25

is $5^2$.

In [101]:
27**(1/3)
Out[101]:
3.0

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:

if <CONDITION>:  
    <BLOCK1>  
else:  
    <BLOCK2>

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:
    print(n)
else:
    print(-n)
5

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:
    print(n)
else:
    print(-n)
5

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

In [105]:
from IPython.display import YouTubeVideo
YouTubeVideo("DvzOjZu0NqI")
Out[105]:

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.)

if <CONDITION1>:
    <BLOCK1>
elif <CONDITION2>:
    <BLOCK2>
elif <CONDITION3>:
    <BLOCK3>
else:
    <BLOCKn>

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)
else:
    print("Go away!") 
Welcome to Port Royal, Jack Sparrow

Tracing if statements

In [120]:
from IPython.display import YouTubeVideo
YouTubeVideo("lf4HDr5GaTM")
Out[120]:

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)
else:
    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")
    else:
        print("Normal QTc")
elif sex == "male":
    if QTc > 470:
        print("Abnormal QTc")
    elif QTc >= 451:
        print("Borderline QTc")
    else:
        print("Normal QTc")

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

Input

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

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

print(a)

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
4242

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
84.0

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")
    else:
        print("Normal QTc")
elif sex == "male":
    if QTc > 470:
        print("Abnormal QTc")
    elif QTc >= 451:
        print("Borderline QTc")
    else:
        print("Normal QTc")

else:
    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]:
%%javascript
$.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js')
In [ ]: