In-class notes for 02/17/2014
CS 121B (CS1), Spring 2014
Submitted questions on assignments and technology
Upcoming
Read online text: Selection
submit at least one reading question by 9am before the next class meeting(If you haven't already, also read Functions and submit at least one reading question by 9am before the next class meeting)
Quiz on Wednesday. See below for topics.
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:
A function
Hint:invite()
with one argument, a list of names, that prints an invitation to a party for each namefor name in ["Joe", "Amy", "Brad", "Angelina", "Zuki"]: print("Hi", name, "Please come to my party on Saturday!")
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 0Add 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 tocount
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 functioninvite()
; also the argument variablesnum1
andnum2
in the functionmean()
; 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
andprint
; arithmetic operators; using variables;for
loops andrange
, similar to homework questions.Turtle graphics:
import turtle
; defining a screen and a turtle; methodsforward()
,left()
,right()
,color()
orpencolor()
< >