Chapter 6

Sections 6.1 - 6.4

\(\boxdot\) Python Functions
  • A Python function is a named sequence of statements that belong together

  • Functions help to organize a program and match the process used to attain a programming objective

  • Functions are constructed using the following syntax:

    def function_name(param_1, param_2, ... param_n):  
        statement 1  
        statement 2  
        ...    
  • Each statement with in the function is indented 4 spaces (like the case of the for loop)

  • The function_name must follow the same naming rules as Python variables, and cannot be a key (reserved) word

  • Functions are run when they are “called” from some other part of the code. This process is known as a function call or function invocation

  • Functions are likely to need inputs to perform the tasks they are designed to do. These input are called parameters. When two or more parameters are required, they are separated by a comma.

  • Some functions do not need parameters. However, the function_name must be followed by an empty set of parentheses

\(\boxdot\) Fruitful and Non-Fruitful Functions
  • fruitful functions are functions that return a value or values. The code below defines a function that returns a str object giving the hours and minutes when the total number of minutes is input. Copy and paste the following code into the pythontutor.com application.

    def hrs_min(min_in):
        hrs = min_in // 60  
        min = min_in % 60  
        return str(hrs) + ':' + str(min)  
    
    
    h_and_m = hrs_min(73)
    print(h_and_m)
  • non-fruitful functions are those that do not return a value or values. The draw_poly function below is an example.

    import turtle
    
    
    def draw_poly(t, n_sides, s_len):
        angle = 360/n_sides
        t.down()
        for side in range(n_sides):
            t.forward(s_len)
            t.left(angle)
        t.up()  
    
    
    wn = turtle.Screen()
    alex = turtle.Turtle()
    draw_poly(alex, 3, 100)
    wn.exitonclick()
  • Activity 1: Modify the code above to include a parameter that will control the line color of the polygon. Next, have the program draw four polygons, with different n_sides, at different locations in the plane.

\(\boxdot\) Local and Global Scopes
  • Load the following code into the pythontutor.com and step through the statements paying close attention to what object have a global frame, and which have a local frame.

    def f(x):
        s = x*x + z
        return s
    
    z = 2
    y = f(3)
    print(y, z)
  • The following code has an error related to variables and their frame. Can you determine what the error is? Load it into the pythontutor.com window and step through to find or confirm the error.

    def f(x):
        z = 2
        s = x*x + z
        return s
    
    y = f(3)
    print(y, z)
\(\boxdot\) Unit Testing
  • Unit testing is a way to ensure a function returns the correct value. Here is an example of how the test module can be used to test certain units or functions within our program.

  • Activity 2: Copy, paste and run the following code into an active code window. (The test module is not known using pythontutor.com.)

    def pyth_theorem(a, b):
        '''find the length of the hypotenuse of a right triangle'''  
        return (a*a + b*b)**0.5  
    
    import test  
    print("testing the pyth_theorem function")
    test.testEqual(pyth_theorem(3, 4), 5)
    test.testEqual(pyth_theorem(1, 2), 5**0.5)
  • Define different scenarios that form equivalence classes and make sure the functions passes the test for each equivalence class. An example is:

    • A function dist(a, b) that calculates the distance (a non-negative value) between two points \(a\) and \(b\) on the \(x\) axis. Possible equivalence classes include:

      • \(a\) and \(b\) positive
      • \(a\) and \(b\) negative
      • \(a\) or \(b\) positive, the other negative

Sections 6.5 - 6.8

\(\boxdot\) Accumulator Pattern
  • A way to keep track of a running total, or accumulation

    value = value + new_term  
  • Important to make sure the value is initalized properly.

  • Activity 3: Write a function called roll_average(roll_list) that uses an accumulator pattern to calculate the average value of the rolls of a die. The function parameter roll_list is a list of values (1, 2, 3, 4, 5 or 6) simulating the results of rolling a six-sided die a certain number of times. The number of rolls (the number of numbers in roll_list) does not need to be a certain size. That is, its length can vary from one call to the next.

\(\boxdot\) Another Unit Test Activity
  • Activity 3.5: An auditorium for stage plays has 20 rows of seats, and each row has 40 seats for a total of 800 seats. Play-goers are assigned to a specific seat based on the number, ranging from 1 (for row 1 and seat 1) to 800 (row 20 and seat 40) printed on their ticket stub. Write a function called row_seat(ticket_number) that takes the ticket number (1 - 800) and returns the row and seat number for the patron.
\(\boxdot\) Functions Calling Functions
  • It is common for a one function to utilize another function in accomplishing a task.

  • Activity 4: Another way to determine the average value for n_rolls of a die is to define two functions. The first is named create_list(n_rolls). This function creates a list used to count the number of times a number between 1-6 is rolled when the die is rolled n_times. Once the counter list has been filled, create_list will call the function list_average(l_in) that calculates the average value based on the values given in the count list.

\(\boxdot\) Flow of Execution
  • Activity 5: Copy and paste the results of the function calling function result into the pythontutor.com code window. Before using the application to follow the flow of execution with this code, determine the correct sequence of line number execution. Then, use step-by-step analysis to visualize the actual flow.
\(\boxdot\) The main() Function
  • The “left-over” statements not in a defined function block can be collected to form the main() function.

  • Some languages require the use of a main function, Python does not.

  • The main() function must be invoked like any other function. It may receive one or more parameters as well.

  • The conventional structure of a Python program:

    • Begin with any required import statements for modules

    • Define any non-main functions, as many as wanted.

    • End with the main() function and the invoking line.

  • Before execution of your program, the Python interpreter defines some special variables including __name__.

    • It is automatically set to main() when the program is running in a standalone fashion

    • If the code is being used by another module, then __name__ is set the module’s name.

  • Activity 6: Modify the code for drawing a grid and graph and plot to include a main() function.

Sections 6.9 - 6.11

\(\boxdot\) Program Development
  • Start with a skeleton version of a program

  • Use temporary variables for testing

  • Once running correctly, consolidate if useful

  • Document important features - functions, etc…

  • Generalize aspects if useful

  • Make it more user-friendly and more fool-proof for others and you, even

\(\boxdot\) Composition
  • Great feature of Python

  • As an example…

    us_dollars = float(input("Pease input the US dollar amount: "))
\(\boxdot\) Further Activities
  • Activity 7: Modify the function plotting code to include the use of functions. Define a function for each of the following tasks:

    • drawing the \(x\)-axis : parameters are the turtle name, x_min, and x_max

    • drawing the \(y\)-axis : parameters are the turtle name, x_min, and x_max

    • drawing the ticks on the \(x\)-axis : parameters are the turtle name, x_min, x_max, tick_space, and the tick length

    • drawing the ticks on the \(y\)-axis : parameters are the turtle name, x_min, x_max, tick_space, and the tick length

    • plotting the function : parameters are the turtle name, x_min, x_max, and the x_space

    • defining the function to be plotted : parameter is the \(x\) value

    • using a main() function for controling the flow of the program

  • Activity 8: Write a program the will draw the bar chart graph using a given set of data. Use the turtle module, and set the world coordinates to (-2, -2, 11, 30). The data to use for the bars are defined by the list [6, 12, 2, 15, 17, 1, 28, 23, 14, 5]. Each bar should be one unit wide. Your program should include the following functions (each bullet point corresponds to a function) that:

    • draws the \(x\)-axis

    • draws the \(y\)-axis

    • draws horizontal lines (like you would draw tick marks) with a vertical spacing of 2 units.

    • draws a bar of height corresponding to the data value through the use of a draw_bar() function. Each bar should be one unit wide.
    • Modify the bar chart code to create a bar chart of the relative distribition of the outcomes of rolling a die \(n\) times.

    • Modify the draw_bar() function so that the bar width is a parameter.

      # Name:
      import turtle
      
      def draw_x_axis(t, x_min, x_max):
          t.up()  
          t.goto(x_min, 0.0)  
          t.down()  
          t.goto(x_max, 0.0)  
          t.up() 
          return
      
      
      def draw_y_axis(t, y_min, y_max):
          t.up()  
          t.goto(0.0, y_min)  
          t.down()  
          t.goto(0.0, y_max)  
          t.up()
          return
      
      
      def tick_y_axis(t, y_min, y_max, y_t_space, x_min, x_max):
          n_y_ticks = int((y_max - y_min)/y_t_space) + 1  
          for tick in range(n_y_ticks):  
              loc = y_min + tick*y_t_space  
              t.up()  
              t.goto(x_min, loc)  
              t.down()  
              t.goto(x_max, loc)  
              t.up()  
          return
      
      
      def draw_bar(t, height, width):
          t.down()
          t.forward(width)
          t.left(90)
          t.forward(height)
          t.left(90)
          t.forward(width)
          t.left(90)
          t.forward(height)
          t.left(90)
          t.up()
          return
      
      
      def main():
          wn=turtle.Screen()
          x_min = -1
          x_max = 11
          y_min = -1
          y_max = 30
          data = [6, 12, 2, 15, 17, 1, 28, 23, 14, 5]
          t_space = 2
          wdt = 1
          wn.setworldcoordinates(x_min, y_min, x_max, y_max)
          a = turtle.Turtle()
          wn.tracer(6, 1)
          draw_x_axis(a, x_min, x_max)
          draw_y_axis(a, y_min, y_max)
          tick_y_axis(a, y_min, y_max, t_space, x_min, x_max)
          a.up()
          x_loc = 0
          for hgt in data:
              a.goto(x_loc,0)
              draw_bar(a,hgt,wdt)
              x_loc += wdt
          wn.exitonclick()
      
      
      main()
\(\boxdot\) Homework Comments
  • Assignment 9

    import turtle  
    
    
     def drawSquare(t,sl):  
         for i in range(4):  
             t.forward(sl)  
             t.right(90)  
    
    
     alex = turtle.Turtle()  
     wn = turtle.Screen()  
     wn.tracer(0)  
     wn.bgcolor('lightgreen')  
     alex.color('blue')  
    
     for i in range(20):  
         drawSquare(alex, 80)  
         alex.right(18) 
    wn.update()
    wn.exitonclick()
  • Assignment 10 - mySqrt(n) function

    • cannot change the name of the function

    • cannot add or delete from the parameter list

    • do not use an input() statements within the function

    • the first guess, oldguess = n / 2, must come before the loop begins