CS 111 - 3/1/18 What is the value of z when this code is finished executing? x = 5 # x: 5 7 z = 1 # z: 1 3 if ( x > 3 ): x = x + 2 z = z + 2 if ( x <= 6 ): x = x + 1 z = z + 1 a. 1 b. 2 c. 3 d. 4 e. 5 What is the value of z when this code is finished executing? x = 5 # x: 5 6 z = 1 # z: 1 2 if ( x >= 6 ): x = x + 2 z = z + 2 else : x = x + 1 z = z + 1 a. 1 b. 2 c. 3 d. 4 e. 5 If statements If-then statement If-else statement This algorithm to reduce the amount of colors being used in a picture is often called: "Posterization" 2 examples of a 2 color Posterization What is the code for a 4 color posterization using blue, red, green, yellow if ( brightness < 128 ) : if ( brightness < 64 ) : # range from 0 - 63 setRed ( pixel, 0) setGreen ( pixel, 0 ) setBlue ( pixel, 255 ) else: # range from 64 - 127 setRed ( pixel, 255 ) setGreen ( pixel, 0 ) setBlue ( pixel, 0 ) else: if ( brightness < 192 ) : # range from 128 - 191 setRed ( pixel, 0) setGreen ( pixel, 255 ) setBlue ( pixel, 0 ) else: # range from 192 - 255 setRed ( pixel, 255 ) setGreen ( pixel, 255 ) setBlue ( pixel, 0 ) The above nested if-else statements does work, but the code is somewhat "ugly" IF Statements additional syntax elif Syntax: if : elif : elif : elif : ... else: If is TRUE, execute Else If is TRUE, execute Else If is TRUE, execute Else If is TRUE, execute ... Else if all of the above conditions are FALSE, execute if ( brightness < 64 ) : # range from 0 - 63 setRed ( pixel, 0) setGreen ( pixel, 0 ) setBlue ( pixel, 255 ) elif ( brightness < 128 ): # range from 64 - 127 setRed ( pixel, 255 ) setGreen ( pixel, 0 ) setBlue ( pixel, 0 ) elif ( brightness < 192 ) : # range from 128 - 191 setRed ( pixel, 0) setGreen ( pixel, 255 ) setBlue ( pixel, 0 ) else: # range from 192 - 255 setRed ( pixel, 255 ) setGreen ( pixel, 255 ) setBlue ( pixel, 0 ) Boolean Operators AND (binary operator) boolean1 AND boolean2 OR (binary operator) boolean1 OR boolean2 NOT (unary operator) NOT boolean NOTE: in python the above operators are written in lower case To check if a value is within a specific range, the most common way to write is: (if val1 in the range from 10 to 20, inclusive) val1 = input ("Enter a numeric value") if ( val1 >= 10 ) and (val1 <= 20 ) : print ("The value enter is in the range from 10 to 20") For AND: the result of the boolean expression is TRUE when BOTH operands are TRUE otherwise the result is FALSE