COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364:...

28
1/28 COMP 364: Conditional Statements Control Flow Carlos G. Oliver , Christopher Cameron September 15, 2017

Transcript of COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364:...

Page 1: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

1/28

COMP 364: Conditional Statements ControlFlow

Carlos G. Oliver, Christopher Cameron

September 15, 2017

Page 2: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

2/28

Outline

1. New midterm date → Tuesday October 24 19:00-21:00ENGMC 204

2. Recap

3. Conditionals (if, else, elif)

4. User input

Page 3: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

3/28

iPython vs command line

I The interactive Python interpreter is not the same as theTerminal/Command Prompt

I Interactive Python prints the result of evaluating anexpression. (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

Page 4: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

4/28

Refresher: the OS and file system

I The Terminal / Command line lets you execute programs (e.g.ls, cd, dir, python, mkdir)

I How to open terminal in Mac and in Windows

I Syntax: $ [program name] [program options]

I These functions includeI Launch the Python interpreter $ pythonI List files in your current directory $ dir $ lsI Change directories $ cd [destination path]

I A program you are executing can only see files in your currentdirectory.

I If you want to access a file outside of your current directoryyou must specify its path in [program options]. (quickdemo)

I e.g. $ python /Users/carlos/Desktop/hello.py willwork from anywhere because it has the full path to the file.

Page 5: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

5/28

Functions are objects

I A function is also an Object which can execute somecommands given an (optional) input to produce an output.

I function name(input)

I e.g. >>> print("Hello world")

Input Function Output

Page 6: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

6/28

Names, Namespaces, Objects

class / type

o2o1 o3

bob alice eve Names

Objects

Namespace

Page 7: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

7/28

Making decisions: conditional statements

I Programs often have to make decisions that depend on someconditions.

I For example, depending on what you type into a Googlesearch, it executes a different set of commands

I Python lets us accomplish this using conditional statements

1

1Rick and Morty

Page 8: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

8/28

An example:finding genes

I Genes are DNA sequences made up of codons that getconverted into proteins.

I We know that they always start with the letters: “AUG”

I We can use the if statement to check if an object is a startcodon.

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

Page 9: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

9/28

A little terminology: Expressions and Operators

I Expressions are any line of code that can be evaluated tosome value and stored as an object.

I Operators do computations on expressions (e.g. +,-,==,

<=, >=, %) to produce new expressions.

I 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 sowe can have a common language when talking about code.

Page 10: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

10/28

A little more terminology: Statements

I Statements are “special” instructions that tell Python howto execute code. (e.g. x = 2, if, else)

I 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,otherwise it is a statement.

Page 11: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

11/28

Back to the if statement

I Python executes line by line going down your code. However,if statments (and others) let us intervene.

I The if statement lets us split our commands into “separate”units that execute based on the value of some booleanexpression.

I Code belonging to an if/else is denoted by a tab (4 spaces)

I Syntax: if (boolean expression) :, else:

I Note: here, the else is not mandatory but can come in handy.

Page 12: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

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)

Page 13: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

13/28

Control Flow

s = "AAgU"

if not s.upper()

print("OK")s.upper()

print("done")

Page 14: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

14/28

Control flow

s = "AAGU"

if not s.upper()

print("OK")s.upper()

print("done")

Page 15: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

15/28

What if we have more than two cases? → elif

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

I Note: as soon as ONE of the cases is True the rest does notexecute (even if they happen to be True as well. Try it!).

Page 16: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

16/28

Else if: elif

I elif always comes after an if or another elif and the laststatement must be an else

I “If the previous if or elif did not evaluate to True ANDthis elif is True execute this block of code.”

I Useful for when you have multiple cases but only one shouldexecute.

I Important: vertical alignment is crucial.

Page 17: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

17/28

Nested if/else/elif statementsI We can put if/else/elif statements inside other

if/else/elif statements.I 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

Page 18: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

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

Page 19: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

19/28

An interlude: interacting with the userI Code is not very useful if it can’t receive information from a

user.I Receiving information → input.

3

3http://www4.pictures.zimbio.com/gi/Kim+Kardashian+eBay+

Holiday+Store+opmeLl_yL8ql.jpg

Page 20: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

20/28

Interactive user input: input()

I The input() function lets us store values into string objectsbased on text given to us while the program is running.

I a.k.a at “runtime”

I Synatx: x = input("Message to user ")

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

Page 21: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

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

Page 22: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

22/28

Sanity checks: assert statements

I Often you want to make sure your code doesn’t do somethingthat makes no sense.

I This comes up a lot in user input since we can’t predict whatthe user will input.

I The assert statement takes a boolean expression. If itevaluates 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)

Page 23: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

23/28

In-class problem: mini medical diagnosis program

I Let’s write a program that takes info on a patient’s symptomsand outputs a diagnosis.

4

4http://house.wikia.com/wiki/File:House328.jpg

Page 24: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

24/28

In class problem: house.py

I Since it may get a little long and we would like to reuse it, weshould save our code in a file house.py (or a notebook).

I Input: age, sex, temperature, coughing, headaches, nausea

I Output: "healthy", or "infection", or "hypothermia",or "pregnant", or "food poisoning"

Page 25: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

25/28

RTFM: Documentation

I Everything I am showing you and much much more isdocumented in the python docs for bulit-in functions.

I The entire set of default python commands and data types ishere

I How to read documentation syntax (live demo)

5

5http://i0.kym-cdn.com/photos/images/newsfeed/000/131/662/

22711800_646849b145.jpg

Page 26: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

26/28

Collections

I The world is full of collections of things. We would like to beable to work with such things efficiently.

6

6Rick and Morty

Page 27: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

27/28

How can we keep track of all the Jerrys?

I We know how to store data as objects. So let’s make anobject 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.

Page 28: COMP 364: Conditional Statements Control Flowblanchem/204/Slides/COMP364_F17_L5.pdf · COMP 364: Conditional Statements Control Flow Carlos G. Oliver, Christopher Cameron September

28/28

Lists

I Just like everything in Python, a list is an Object of type list.

I We store a list using square brackets [] and separate objectswith commas (,).

1 >>> jerrys = ["Original jerry", "Clone one", "Clone

two"]↪→

2 >>> type(jerrys)

3 <class ‘list’>

4 >>> id(jerrys)

5 4339082696