CMIS 102 if So far, all the programs we've seen and done have used only sequence as the flow of control. The programs have only used the calculator aspects of the computer: get some input, store it, calculate with it, output the results. The computer is differentiated from a calculator by its ability to ask a question and do one thing or the other depending on the answer to the question. In other words, it can make decisions and select one statement or another to execute; it's not limited to executing each and every statement in the order in which they appear in the program. We look now at selection, or branching, control construct. A question or a condition is posed, the answer of which is True or False (there can't and won't be "maybe" answers). Technically, it is an "assertion", but it's easier to think of it as a question. A typical question is asking if the value of variable num is greater than 0, which would be expressed as: num > 0 Selection is done with the "if" statement: if num > 0: print("num is greater than 0") # TRUE branch else: print("num is not greater than 0") # FALSE branch If the answer is True then the TRUE branch is taken, but if the answer is False (i.e. num is less than or equal to 0) then the FALSE branch is taken. One or the other is executed, not both and not neither. Each of the True and False branches can consist of any number and kinds of statements. It's like human language and logic. From the moment you awaken you are doing "if" statements: If I'm really groggy then I will hit the snooze button, else I get up now. If I have time then I will cook a breakfast else I will eat a pop tart. #minimum of two numbers x = float(input("Enter x: ")) y = float(input("Enter y: ")) if x < y: min = x else: min = y #what if x equals y? print("Min is", min) "if" and "else" are reserved/key words. Every if statement has an expression which is the condition. Notice that there is a : after the condition. The condition is followed by the statement or statements, called the "body", of the if, that is/are executed if the condition is True. Each statement of the body must be indented. The body of the if is then [optionally] followed by the else and its body which is executed if the condition is False. An else is never by itself, it always is part of an if statement. Note that some of the standard math symbols are not available, so Python's "comparison" operators are composed: <, >, <=, >=, == (equality), != (not equals). Notice that the statements of the body are indented relative to the if and else. That is mandatory. The else part is optional. A classic error is to confuse the = with the ==. Python is not math. = is assignment, == is equality. Try this wrong code: x = 3 y = 3 if x = y: #syntax error. should be == of course print("they are equal") else: print("they are different") In a mileage program, we could check that the start and ending miles are somewhat meaningful by this: startMiles = eval(input("Enter start miles: ")) endMiles = eval(input("Enter end miles: ")) if startMiles > endMiles: print("Error! Starting mileage can't be more than ending mileage") else: #continue with the rest of the program.... print("ok to continue...") In a triangle program we could "sanity" check the two lengths to make sure they are positive numbers: lengthOfA = eval(input("Enter length of side A: ")) lengthOfB = eval(input("Enter length of side B: ")) if lengthOfA <= 0: print("Error! Length of A must be positive") if lengthOfB <= 0: print("Error! Length of B must be positive") The condition can be any expression. Here are some examples using arithmetic and relational operators: if x <= y/2: ... if x > math.sqrt(y)+1: ... if x/2 < y+z: ... The statements in a body can be anything, including an if statement. "Nested" if statements are common. There's no limit on the level of nesting, it's whatever the problem solution requires. Here's an example: x = eval(input("Enter number: ")) y = eval(input("Enter divisor: ")) if y != 0: x = 1 / y print("Reciprocal is:", x) else: print("No division by zero") if y != 0: result = x / y if result < 0: print("negative result") else: print("positive result") else: result = 0 print("Zero divisor!") Here's an alternate way to do the same: if y == 0: result = 0 print("Zero divisor!") else: result = x / y if result < 0: print("negative result") else: print("positive result") Did you notice that these two code fragments are logically identical? They accomplish exactly the same thing. You should be thinking that the level of material seems to have increased in difficulty. It has. We are starting to get into the real meat of programming, which is complexity: the complexity of the real world and thus the complexity of software that models and interacts with the real world. And remember that the computer is a mindless machine that only does what you tell it to do, and you have to be very precise about what you say. That's why programming languages are so detailed. And programming is so hard. # counting asterisks and all other chars #assume stars and non_stars already defined c = input("Enter a character: ") if c == '*': stars = stars + 1 print("Another star") else: non_stars = non_stars + 1 print("Another non star") if c == '*': stars = stars + 1 if stars > 100: print("More than 100 stars") else: #matches the outer if by its indentation level print("A non star") #not counting other chars if c == '*': stars = stars + 1 if stars > 100: again = 'y' print("More than 100 stars") else: print("Less than 100 stars") else: non_stars = non_stars + 1 print("Another non star") password = input("Enter the secret word: ") if password == "arfarf": #compare two strings for equality print("You win!") else: print("Sorry") weight = float(input("Enter your weight: ")) units = input("(k)g or (l)bs? ").upper() if units == 'K': print("Your weight in pounds is:", weight*2.2) else: print("Your weight in kilos is:", weight/2.2) ******************** any value not zero is considered true: 12, "hello", The 'zeroes' are false: 0, 0.0, "", None Also: [], (), {}, set(), 0j