The following are examples of the kinds of Python expressions that we can use.
4 + 5
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.
3 == 4
4 == 4
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.
"ha" * 10
"ha" + "hah"
Note that you can have any text at all encolsed in quotes:
"the number" + " " + "42"
"hi" == "hello"
"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
memory = 42
We can now retrieve the value that we stored in memory by typing memory in the shell
memory
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.)
lol = 101
hours_of_sleep = 2
We computed things like 42 + 5 before. We can also use variables in place of actual numbers:
hours_of_sleep + .15
We can assign values that are computed like to to variables:
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:
with_snooze
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:
print(with_snooze)
print(with_snooze + .15)
print("hi")
Here is a silly program (copy and paste it into Pyzo, and use Cntrl-E (or Cmd-E on Mac) to run it.)
hours_of_sleep_weekend = 20
print(4 + 5)
"lol"
print(15 - 12)
hours_of_sleep_weekend
5 + 10
"lol"
print("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.
Note that strings are enclosed in quotes, and variables are not. For example, consider this:
a = hello
print(a)
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:
a = "hello"
print(a)
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.
hello = "bye"
a = hello
print(a)
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.
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)
from IPython.display import YouTubeVideo
YouTubeVideo("0FasnsuPbjg")
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.
print("Hello Python")
print("Oh, I guess you're here too, hi")
Now, let's write our first "substantive" program. Here, we are giving the computer instructions about how to transform a "secret" number.
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)
The math works out in such a way that you get 4.0 no matter what the secret number is:
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)
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.
from IPython.display import YouTubeVideo
YouTubeVideo("Mw03-479UYw")
A note about print: you can print multiple things at once by separating the things you want to print with commas.
print("hi", "there")
print("hi", 5)
print("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:
print("C4" + "M")
This is in contradistinction to:
print("C4", "M")
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.
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 + ".")
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:
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)
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
5**2
is $5^2$.
27**(1/3)
is $27^{\frac{1}{3}} = \sqrt[3]{27}$.
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.
HR = 70
QT = 300 #in milliseconds
RR = 60/HR
QTc = QT/(RR**(1/3))
print("Correct QT Interval:", QTc, "milliseconds")
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).
n = -5
if n >= 0:
print(n)
else:
print(-n)
Note that only one of the lines with print is ever executed. If n is positive, then only the first print will run:
n = 5
if n >= 0:
print(n)
else:
print(-n)
Here is a more complicated example (see the video below).
from IPython.display import YouTubeVideo
YouTubeVideo("DvzOjZu0NqI")
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!
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!")
from IPython.display import YouTubeVideo
YouTubeVideo("lf4HDr5GaTM")
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.
greetee = "Dr. Evil"
if greetee == "Lord Voldermort":
print("Hello", greetee)
else:
print("I'm not talking to you")
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."
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")
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.
name = input("What is your name? ")
#User types in the name and presses Enter now
print("Hi", name)
There is one issue: input() always returns a string -- text that we've been enclosing in quotes. Imagine that we have
n = input("Enter a number: ")
#user types in 42, so n is "42"
print(n * 2) #prints 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:
n = float(input("Enter a number:"))
#user types in 42, so n is 42
print(n * 2) #prints 82.0
Write a program that asks the user for their sex, QT interval, and heartrate, and outputs whether their QTc is normal/borderline/abnormal.
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")
%%javascript
$.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js')