1/28
COMP 364: Conditional Statements Control Flow Carlos G. Oliver, - - PowerPoint PPT Presentation
COMP 364: Conditional Statements Control Flow Carlos G. Oliver, - - PowerPoint PPT Presentation
COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September 15, 2017 1/28 Outline 1. New midterm date Tuesday October 24 19:00-21:00 ENGMC 204 2. Recap 3. Conditionals (if, else, elif) 4. User input
2/28
Outline
- 1. New midterm date → Tuesday October 24 19:00-21:00
ENGMC 204
- 2. Recap
- 3. Conditionals (if, else, elif)
- 4. User input
3/28
iPython vs command line
◮ The interactive Python interpreter is not the same as the
Terminal/Command Prompt
◮ Interactive Python prints the result of evaluating an
- expression. (more later)
1
>>> "hello"
2
"hello" #interactive python automatically prints result of expression
֒ → 3
>>> print("hello") #this is the same as above
4
"hello"
5
>>> s = "hello" #will not print anything
4/28
Refresher: the OS and file system
◮ The Terminal / Command line lets you execute programs (e.g.
ls, cd, dir, python, mkdir)
◮ How to open terminal in Mac and in Windows ◮ Syntax: $ [program name] [program options] ◮ These functions include
◮ Launch the Python interpreter $ python ◮ List files in your current directory $ dir $ ls ◮ Change directories $ cd [destination path]
◮ A program you are executing can only see files in your current
directory.
◮ If you want to access a file outside of your current directory
you must specify its path in [program options]. (quick demo)
◮ e.g. $ python /Users/carlos/Desktop/hello.py will
work from anywhere because it has the full path to the file.
5/28
Functions are objects
◮ A function is also an Object which can execute some
commands given an (optional) input to produce an output.
◮ function name(input) ◮ e.g. >>> print("Hello world")
Input Function Output
6/28
Names, Namespaces, Objects
class / type
- 2
- 1
- 3
bob alice eve Names Objects Namespace
7/28
Making decisions: conditional statements
◮ Programs often have to make decisions that depend on some
conditions.
◮ For example, depending on what you type into a Google
search, it executes a different set of commands
◮ Python lets us accomplish this using conditional statements 1
1Rick and Morty
8/28
An example:finding genes
◮ Genes are DNA sequences made up of codons that get
converted into proteins.
◮ We know that they always start with the letters: “AUG” ◮ We can use the if statement to check if an object is a start
codon.
1
codon = "AAG"
2 3
if codon == "AUG":
4
print("This is a start codon!")
5
else:
6
#if we have a start codon, this NEVER executes
֒ → 7
print("This is not a start codon!")
9/28
A little terminology: Expressions and Operators
◮ Expressions are any line of code that can be evaluated to
some value and stored as an object.
◮ Operators do computations on expressions (e.g. +,-,==,
<=, >=, %) to produce new expressions.
◮ You can think of operators as special tokens for functions.
Life Hack 1 Don’t worry too much about all this terminology. It’s just so we can have a common language when talking about code.
10/28
A little more terminology: Statements
◮ Statements are “special” instructions that tell Python how
to execute code. (e.g. x = 2, if, else)
◮ They do not evaluate to a value. (e.g. if is a statement, x =
4 is also a statement)
1
>>> x = 3 #statement
2
>>> y = 9 # statement
3
>>> x + y # expression
4
12 Life Hack 2 If you can print it or assign a name to it it’s an expression,
- therwise it is a statement.
11/28
Back to the if statement
◮ Python executes line by line going down your code. However,
if statments (and others) let us intervene.
◮ The if statement lets us split our commands into “separate”
units that execute based on the value of some boolean expression.
◮ Code belonging to an if/else is denoted by a tab (4 spaces) ◮ Syntax: if (boolean expression) :, else: ◮ Note: here, the else is not mandatory but can come in handy.
12/28
Small example
1
sequence = "AACGAAgU"
2 3
if not s.isupper():
4
#inside first case
5
#DNA sequence not capitalized
6
print("You forgot to capitalize")
7
sequence = sequence.upper()
8
print("I fixed it")
9
else:
10
#inside second case
11
# DNA sequence correct
12
print("Sequence OK")
13 14
#outside if statement
15
print(sequence)
13/28
Control Flow
s = "AAgU" if not s.upper() print("OK") s.upper() print("done")
14/28
Control flow
s = "AAGU" if not s.upper() print("OK") s.upper() print("done")
15/28
What if we have more than two cases? → elif
◮ Let’s try to figure out if we have a natural disaster.
1
ground_shaking = True
2
flooding = False
3 4
if(ground_shaking and not flooding):
5
print("Earthquake!")
6
elif(not ground_shaking and flooding):
7
print("Hurricane!")
8
elif(ground_shaking and flooding):
9
print("End of the world!")
10
else:
11
print("Everything is okay.")
◮ Note:
as soon as ONE of the cases is True the rest does not execute (even if they happen to be True as well. Try it!).
16/28
Else if: elif
◮ elif always comes after an if or another elif and the last
statement must be an else
◮ “If the previous if or elif did not evaluate to True AND
this elif is True execute this block of code.”
◮ Useful for when you have multiple cases but only one should
execute.
◮ Important: vertical alignment is crucial.
17/28
Nested if/else/elif statements
◮ We can put if/else/elif statements inside other
if/else/elif statements.
◮ Note:
can lead to repetitive code so elif is preferred when applicable.
2
2http:
//wallpoper.com/images/00/21/28/83/movie-inception_00212883.jpg
18/28
Nested if statements
1
ground_shaking = True
2
flooding = False
3 4
if ground_shaking:
5
if flooding:
6
print("End of the world!")
7
else:
8
print("Earthquake!")
9
else:
10
if flooding:
11
print("Hurricane!")
12
else:
13
print("Everything is okay.")
19/28
An interlude: interacting with the user
◮ Code is not very useful if it can’t receive information from a
user.
◮ Receiving information → input. 3
3http://www4.pictures.zimbio.com/gi/Kim+Kardashian+eBay+
Holiday+Store+opmeLl_yL8ql.jpg
20/28
Interactive user input: input()
◮ The input() function lets us store values into string objects
based on text given to us while the program is running.
◮ a.k.a at “runtime” ◮ Synatx: x = input("Message to user ") ◮ Convert the input to the appropriate data type using: int(),
float(), bool()
1
flooding = input("Is there flooding? (Y/N)")
2
if flooding == "Y":
3
flooding = True
4
elif flooding == "N":
5
flooding = False
6
else:
7
print("Incorrect input format, enter Y/N")
21/28
Example
1
flooding = input("Is there flooding? (True/False) ")
2
ground_shaking = input("Is the ground shaking? ")
3 4
#leaving out the type conversions for brevity (see prev slide for example)
֒ → 5 6
if(ground_shaking and not flooding):
7
print("Earthquake!")
8
elif(not ground_shaking and flooding):
9
print("Hurricane!")
10
elif(ground_shaking and flooding):
11
print("End of the world!")
12
else:
13
print("Everything is okay.")
22/28
Sanity checks: assert statements
◮ Often you want to make sure your code doesn’t do something
that makes no sense.
◮ This comes up a lot in user input since we can’t predict what
the user will input.
◮ The assert statement takes a boolean expression. If it
evaluates to false, the program terminates.
1
#this code divides two user input numbers
2
numerator = int(input("Give me a number: "))
3
denominator = int(input("Give me a number: "))
4
assert denominator != 0
5
print(numerator / denominator)
23/28
In-class problem: mini medical diagnosis program
◮ Let’s write a program that takes info on a patient’s symptoms
and outputs a diagnosis.
4
4http://house.wikia.com/wiki/File:House328.jpg
24/28
In class problem: house.py
◮ Since it may get a little long and we would like to reuse it, we
should save our code in a file house.py (or a notebook).
◮ Input:
age, sex, temperature, coughing, headaches, nausea
◮ Output:
"healthy", or "infection", or "hypothermia",
- r "pregnant", or "food poisoning"
25/28
RTFM: Documentation
◮ Everything I am showing you and much much more is
documented in the python docs for bulit-in functions.
◮ The entire set of default python commands and data types is
here
◮ How to read documentation syntax (live demo) 5
5http://i0.kym-cdn.com/photos/images/newsfeed/000/131/662/
22711800_646849b145.jpg
26/28
Collections
◮ The world is full of collections of things. We would like to be
able to work with such things efficiently.
6
6Rick and Morty
27/28
How can we keep track of all the Jerrys?
◮ We know how to store data as objects. So let’s make an
- bject for each Jerry.
1
jerry1 = "Original"
2
jerry2 = "First clone"
3
jerry3 = "Second clone" This doesn’t seem like a very efficient way of doing things. Thankfully Python lets us store collections of things very easily.
28/28
Lists
◮ Just like everything in Python, a list is an Object of type list. ◮ We store a list using square brackets [] and separate objects
with commas (,).
1
>>> jerrys = ["Original jerry", "Clone one", "Clone two"]
֒ → 2
>>> type(jerrys)
3
<class ‘list’>
4
>>> id(jerrys)
5