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
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) >>> "hello" 1 "hello" #interactive python automatically 2 prints result of expression ֒ → >>> print("hello") #this is the same as above 3 "hello" 4 >>> s = "hello" #will not print anything 5 3/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. 4/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 Output Function 5/28
Names, Namespaces, Objects class / type Objects o1 o2 o3 eve bob alice Names Namespace 6/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 1 Rick and Morty 7/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. codon = "AAG" 1 2 if codon == "AUG": 3 print("This is a start codon!") 4 else: 5 #if we have a start codon, this NEVER 6 executes ֒ → print("This is not a start codon!") 7 8/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. 9/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) >>> x = 3 #statement 1 >>> y = 9 # statement 2 >>> x + y # expression 3 12 4 Life Hack 2 If you can print it or assign a name to it it’s an expression , otherwise it is a statement . 10/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. 11/28
Small example sequence = "AACGAAgU" 1 2 if not s.isupper(): 3 #inside first case 4 #DNA sequence not capitalized 5 print("You forgot to capitalize") 6 sequence = sequence.upper() 7 print("I fixed it") 8 else: 9 #inside second case 10 # DNA sequence correct 11 print("Sequence OK") 12 13 #outside if statement 14 print(sequence) 15 12/28
Control Flow s = "AAgU" if not s.upper() s.upper() print("OK") print("done") 13/28
Control flow s = "AAGU" if not s.upper() s.upper() print("OK") print("done") 14/28
What if we have more than two cases? → elif ◮ Let’s try to figure out if we have a natural disaster. ground_shaking = True 1 flooding = False 2 3 if(ground_shaking and not flooding): 4 print("Earthquake!") 5 elif(not ground_shaking and flooding): 6 print("Hurricane!") 7 elif(ground_shaking and flooding): 8 print("End of the world!") 9 else: 10 print("Everything is okay.") 11 ◮ 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!). 15/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. 16/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 2 http: //wallpoper.com/images/00/21/28/83/movie-inception_00212883.jpg 17/28
Nested if statements ground_shaking = True 1 flooding = False 2 3 if ground_shaking: 4 if flooding: 5 print("End of the world!") 6 else: 7 print("Earthquake!") 8 else: 9 if flooding: 10 print("Hurricane!") 11 else: 12 print("Everything is okay.") 13 18/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 3 http://www4.pictures.zimbio.com/gi/Kim+Kardashian+eBay+ Holiday+Store+opmeLl_yL8ql.jpg 19/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() flooding = input("Is there flooding? (Y/N)") 1 if flooding == "Y": 2 flooding = True 3 elif flooding == "N": 4 flooding = False 5 else: 6 print("Incorrect input format, enter Y/N") 7 20/28
Example flooding = input("Is there flooding? (True/False) ") 1 ground_shaking = input("Is the ground shaking? ") 2 3 #leaving out the type conversions for brevity (see 4 prev slide for example) ֒ → 5 if(ground_shaking and not flooding): 6 print("Earthquake!") 7 elif(not ground_shaking and flooding): 8 print("Hurricane!") 9 elif(ground_shaking and flooding): 10 print("End of the world!") 11 else: 12 print("Everything is okay.") 13 21/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. #this code divides two user input numbers 1 numerator = int(input("Give me a number: ")) 2 denominator = int(input("Give me a number: ")) 3 assert denominator != 0 4 print(numerator / denominator) 5 22/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 4 http://house.wikia.com/wiki/File:House328.jpg 23/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" , or "pregnant" , or "food poisoning" 24/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 5 http://i0.kym-cdn.com/photos/images/newsfeed/000/131/662/ 22711800_646849b145.jpg 25/28
Collections ◮ The world is full of collections of things. We would like to be able to work with such things efficiently. 6 6 Rick and Morty 26/28
How can we keep track of all the Jerrys? ◮ We know how to store data as objects. So let’s make an object for each Jerry. jerry1 = "Original" 1 jerry2 = "First clone" 2 jerry3 = "Second clone" 3 This doesn’t seem like a very efficient way of doing things. Thankfully Python lets us store collections of things very easily. 27/28
Recommend
More recommend