# conditionals.py # You need to understand boolean expressions to understand conditionals. # If you are not familiar with them, consult [Downey]. # absolute taking one argument returns the absolute value of the given # number. To compute the absolute value, it uses a conditional # expression, i.e., if...else... Both syntax and semantics of a # conditional expression is intuitive. # def absolute(x): if x < 0: return -x else: return x absolute(-34) # silent print absolute(-34.4) # not silent # A conditional expression can be of the cascaded if...elif... ...else... # form if you need to have multiple cases to handle, again intuitive. # Note, that if you define functions with the same name multiple times, # the last one overwrites all the previous ones even if their signatures # are different (unlike how it is in Java. Java supports function name # overloading, but not in Python.). # def absolute(x): if x < 0: return -x elif x > 0: return x else: return 0 print "absolute(-34) = ", absolute(-34) print "absolute(34) = ", absolute(34) print "absolute(0) = ", absolute(0) # Exercise 1: # # Write a boolean function that determines if a given speed value is within # the legal freeway speed on I-10 outside of the city limits. Once you define # the function, write a piece of code that calls (aka uses/invokes/applies) the # defined function and prints the computed result (true or false). # Exercise 2: # # Given a score out of 100, return a letter grade for the score. Let's assign # the letter grade using the grading scale given by the following table: # # above 89: A # above 79 and below 90: B # above 69 and below 80: C # above 59 and below 70: D # below 60: F # # and call the function at least five times, each time producing a different # letter grade. # # It is okay to produce the final grade as a string value, e.g., "A" for an A. # Exercise 3: # # See Section 5.14 of [Downey] if you want to see more exercise problems. # A side note: In Python a function name cannot be overloaded. That is, you # cannot define a function with different parameter lists to mean different # functions. For example, if you redefine absolute with two parameters, the # one with one parameter that you defined earlier is lost. # # So, you can call absolute with one argument okay here # print absolute(-23) def absolute(x, y): return x + y # But, you cannot call absolute with one parameter here any more, thus I # commented it out here. # # print absolute(-23) # # Of course, this one below would certainly be okay. # print absolute(2, 3)