COP 3223H meeting -*- Outline -*- * Conditionals in Python ** conditional expressions ------------------------------------------ CONDITIONAL EXPRESSIONS Purpose: Syntax: ::= if else Examples: n / d if (d != 0.0) else 10.0 sqrt(n) if n>0 else 0.0 Semantics: ------------------------------------------ ... to give a value that depends on the program's state Show the equivalent syntax in C 2 ? 1 : 3 Examples in C: d!=0.0 ? n/d : 10.0 n>0 ? sqrt(n) : 0.0 The condition (following if) is evaluated first, if the condition is True, then the value is the value of the first expression (before if), otherwise the value is the value of the last expression (after else) ------------------------------------------ AND, OR ARE SYNTACTIC SUGARS e1 and e2 ==> e1 or e2 ==> So "and", "or" are short-curcuit operators, the only evaluate their second argument if necessary Examples: d!=0 and n/d > 3.0 n<0 or sqrt(n) < 100.0 ------------------------------------------ ... e2 if e1 else e1 # e1 is False in the else case ... e2 if (not e1) else e1 # e1 is True in the else case However, these desugarings are a bit of a lie, since e1 is not evaluated twice as it would appear The term "syntactic sugar" means a translation within a language that defines the semantics of one thing (the sugar) in terms of another (the desugared thing) ** conditional statements ------------------------------------------ IF-STATEMENTS Purpose: Syntax: ::= if : | if : else: | if : | if : else: | ... ::= elif : | elif : Examples: if i < len: sum = sum + i if i < len: sum = sum + i else: pass if num == 1: return "one" elif num == 2: return "two" elif num == 3: return "three" else: return "more" Semantics: valuates the first , ------------------------------------------ ... to decide, based on the program's state, what actions to have the program take ... if that is True, then does the corresponding otherwise evaluates each in order (from top left), and runs the corresponding if it is True, if none are True, then runs the following else:, if any Show the syntax in C (but can simplify): ::= if ( ) | if ( ) else | { } ::= ::= | | ::= | ------------------------------------------ FOR YOU TO DO Write a function max(x,y) that returns the larger of the numbers x and y passed as arguments, so that if after res = max(x,y) the following holds: res >= x and res >= y. ------------------------------------------ ... def max(x,y): """Return the maximum of arguments x and y.""" if x > y: return x else: return y