>>     < >




In-class notes for 02/17/2014

CS 121B (CS1), Spring 2014

Submitted questions on assignments and technology

Upcoming

Submitted questions on readings

Functions

  • Function definitions

    Example: Write a function with two numerical arguments that returns the average (mean) of those argument values.

        def mean(num1, num2):
    	return (num1 + num2)/2
    
  • Syntax for a function definition

  • Exercise: write functions that accomplish the following:

    1. A function invite() with one argument, a list of names, that prints an invitation to a party for each name

      Hint:
          for name in ["Joe", "Amy", "Brad", "Angelina", "Zuki"]:
      	print("Hi", name, "Please come to my party on Saturday!")
      
    2. A function square() with two arguments, a turtle and a length, that draws a square using turtle arg1 with arg2 as the length of a side.

Accumulators

  • An accumulator is a variable that collects a desired value during a computation.

  • Example: Consider Friday's in-class exercise.

    • What's needed is a variable for keeping track of how many invitations have been printed.

    • Example accumulator name count

    • Start count at 0

    • Add 1 to count every time another invitation is printed.

    • Then, the final value of count will equal the number of invitations sent.

    • Resulting code:

          count = 0
          for name in ["Joe", "Amy", "Brad", "Angelina", "Zuki"]:
      	print("Hi", name, "Please come to my party on Saturday!")
              count = count + 1
          print(count, "invitations were printed")
      
    • Notes:

      • count = count + 1 adds 1 to count

        Left side uses old value of count

        Right side says where to store the incremented value (i.e., into the same variable count)

      • meaning of count: At any point during the computation, count invitations have been issued.

  • Exercise: Write a loop with an accumulator that returns a sum of a list of integers

  • Exercise: Write a function sumInts() with one argument, a list of integers, that returns the sum of the integers in that list

Function specifications ('specs'), etc.

  • local variables -- only accessible within a function's definition

    E.g., count in the function invite(); also the argument variables num1 and num2 in the function mean(); etc.

  • Specs...

  • Binding and evaluation

To study for quiz

This will be the first of about 10 weekly quizzes, with about 15 min of questions involving the following topics

  • Python3 coding: input and print; arithmetic operators; using variables;

  • for loops and range, similar to homework questions.

  • Turtle graphics: import turtle; defining a screen and a turtle; methods forward(), left(), right(), color() or pencolor()




< >