CS 111 f21 — Better Living Through Functions and Conditionals

Table of Contents

1 Review

  • What will this code print1

    from math import sqrt
    sqrt = sqrt(81)
    print("sqrt =", sqrt(sqrt))
    
  • Order the following lines to correctly print the area of a circle with radius r2

    print("The area of the circle is", area)
    area = math.pi * r**2
    import math
    r = 7.5
    
  • Consider the documentation for math.pow:

    math.pow(x, y):

    Return x raised to the power y.

    How would be change the above code to use math.pow instead of **?3

2 Fuctions!

  • Returning to the get_cur_temp() mystery
    • Called a function (doesn't mean what that means in math class)
    • Separates definition and execution
  • Why should Current Temperature Inc. have all the fun? Let's make our own function!
    • F_to_C function

      def F_to_C(temp_F):
          return (temp_F - 32) * 5 / 9
      
  • All function definitions start out the same way (name, parameters, colon)

    def my_function_name(parameter1, parameter2, ...):
        # the steps inside the function are indented
    # the first unindented line marks the end of the steps of the function
    
    • Function names follow the same rules as variable names
  • The function definition determines the number of parameters and the labels they get inside the function
  • return is a special Python instruction that we use inside functions
    • It causes the function to end (i.e., nothing else inside the function will happen once it gets to return
    • It set the value the function call will have
  • Using a function looks like:

    my_function_name(parameter1_value, parameter2_value, ...)
    
    • This is a function call
    • The result of the function call, the value it will have, is determined by what the function returns
  • Aaron's function manifesto
    • A function should only operate on its parameters or variables defined inside the function (never other variables)
    • Always return a result at the end
  • Class discussion: why might we want to use functions?

3 Quick Check

Define a function that takes the radius and returns the area of a circle, use the function to print the area of a circle of radius 104

4 Decision Time

  • Since the start of the term we've been talking about having a computer make a decision based on some condition (e.g., decide what weather icon to display)
  • We can do this with Python's if

    if CONDITION:
        print("this is only printed when CONDITION is True")
    print("this is always printed")
    
  • We can use if-else to cause the computer to take one of two different paths

    if CONDITION:
        print("this is only printed when CONDITION is True")
    else:
        print("this is only printed when CONDITION is False")
    print("this is always printed")
    
  • Boolean expressions
    • A kind of "math" (CPU opeartion) that results in either True or False
    • Relational operators:
      • less than (<), less than or equal to (<=)
      • greater than (>), greater than or equal to (>=)
      • equal (==), easy to confuse with assignment (=)
      • not equal (!=)
  • Making the text red when the temperature is hot:

    from temperature import get_cur_temp
    
    def F_to_C(temp_F):
        return (temp_F - 32) * 5 / 9
    
    # get data
    cur_temp = get_cur_temp()
    hot_temp = 80
    # convert to Celsius
    hot_temp_C = F_to_C(hot_temp)
    # output temperature
    if cur_temp > hot_temp_C:
        # printing red text from: https://stackoverflow.com/a/21786287
        print("The current temperature is\x1b[1;31;40m", cur_temp, "\x1b[0mdegrees Celsius")
    else:
        print("The current temperature is", cur_temp, "degrees Celsius")
    
  • What if we want the text to have more than settings (normal, yellow, red)?
    • Could do something like

      if cur_temp > hot_temp_C:
          # print in red
      else:
          if cur_temp > hot_temp_C - 5:
             # print in yellow
          else:
             # print normally
      

      but this would quickly get cumbersome with tons of indenting as the number of different outcomes grew

  • Instead, we can use if-elif-else

    if cur_temp > hot_temp_C:
        # print in red
    elif cur_temp > hot_temp_C - 5:
        # print in yellow
    else:
        # print normally
    
  • What if we had multiple conditions?

    if cur_temp > hot_temp_C:
        if chance_of_rain > 0.4:
            # display text in red with cloudy icon
        elif chance_of_clouds > 0.5:
            # display text in red with cloudy icon
    else:
       # ...
    
    • We can use and and or to combine several Boolean expressions into a single condition

      if cur_temp > hot_temp_C and (chance_of_rain > 0.4 or chance_of_clouds > 0.5):
          # display text in red with cloudy icon
      else:
          # ...
      
      • A and B will be True when both A and B are True
      • A or B will be True when either A or B is True
        • Also when both A and B are True

5 Practice

Write an absolute value function: takes one number as a parameter, returns the positive version of that number (hint: if x is negative, -x is the positive version).5

Footnotes:

1

There will be an error on the third line: TypeError: 'float' object is not callable. This is because line 2 replaces the sqrt function we imported from math with the number 9.0.

2
import math
r = 7.5
area = math.pi * r**2
print("The area of the circle is", area)
3
area = math.pi * math.pow(r, 2)
4
import math
def circle_area(radius):
    area = math.pi * radius**2
    return area
print("Area of a circle with radius 10 is", circle_area(10))
5
def abs(x):
    if x < 0:
        return -x
    else:
        return x