Sep 3 2007CS1301 - O'Hara1 CS 1301 Review Keith O’Hara [email protected] .
-
Upload
virginia-bond -
Category
Documents
-
view
217 -
download
3
Transcript of Sep 3 2007CS1301 - O'Hara1 CS 1301 Review Keith O’Hara [email protected] .
Sep 3 2007 CS1301 - O'Hara 1
CS 1301
Review
CS 1301
ReviewKeith O’[email protected]
http://wiki.roboteducation.org
Sep 3 2007 CS1301 - O'Hara 2
Programming JargonProgramming Jargon
Value - fundamental programming quantity with a type Float - 3.0 Integer - 3 String - “3”, “Three” Boolean - True, False
Expression - Evaluates to a value. 3 + 2 - 6 *8
Statement - segment of code python executes and does something print 3 + 2
Variable - name that refers to a value x = 3 + 2
Sep 3 2007 CS1301 - O'Hara 3
ExpressionsExpressions
Code snippets that evaluate to some value. 3**2 #evaluates to 9 (3+2)*(4+2) 3.0/2.0 “hello” + “world” (3 == 4) #evals to False (3 != 4) #evals to True (3 < 4) #evals to True “abc” < “bcd” #evals to True
Sep 3 2007 CS1301 - O'Hara 4
Types of ValuesTypes of Values
Integers (like integers in math) -1, -2, 300000, 0
Floating Points (like “decimals”) -1.5, 1.5, 3.1415, 1.0
Character (like symbol of an alphabet) ‘a’, ‘b’, ‘c’, ‘z’
Strings (a string of characters) “CS”, “1301”, “rocks”
Booleans (a truth value) True or False
Sep 3 2007 CS1301 - O'Hara 5
Have Type-SenseHave Type-Sense
Your expressions should make sense in terms of what type they are
Some make perfect sense 3 + 4 = 7 [int + int = int]
Some expressions make no sense “hello” + 4 [ string + int]
Some expressions make (uncommon) sense 4.0 + 3 [float + int] 4.0 + 3 = 7.0 [float + int = float] “CS” * 3 = “CSCSCS” [string * int = string]
Sep 3 2007 CS1301 - O'Hara 6
Order of OperationsOrder of Operations
Order an expression is evaluated
PEMDAS Parentheses Exponentiation Multiplication, Division Addition, Subtraction
Left-to-Right
(3-2)*(4+2)**2
(1)*(4+2)**2
(1) * (6)**2
(1) * (36)
36
Sep 3 2007 CS1301 - O'Hara 7
VariablesVariables
Variables refer to values b = 3 + 2 # b = 5 a = b * 2 # a = 10 myName = “Keith” inCS1301 = True
“=“ means assignment not equality b = 3 + 2 # store 5 in the variable b b = 3 * 2 # store 6 in the variable bx = x +1
Sep 3 2007 CS1301 - O'Hara 8
StatementsStatements
Code snippets that do stuff! Driving the robot
forward(1, 0.5) stop beep(1, 440)
Assignment classname = “cs1301”
Displaying to the screen print classname print “We love”, classname, “it’s great”
Sep 3 2007 CS1301 - O'Hara 9
Useful FunctionsUseful Functions
A function is a piece of code you can use over and over again Treat it like a black box
You pass it values, it does some work, and it returns values
You “call it”,”invoke it”, or “use it” by using its name and parentheses The things you pass it go inside
the parentheses output = function(input)
function
input
output
Sep 3 2007 CS1301 - O'Hara 10
Using Simple FunctionsUsing Simple Functions
forward(1)
stop()
beep(1, 440)
Functions that interact with the robot forward (speed) beep(time, frequency)
Pass them arguments Execute in sequential
order flow of execution
Top-level not in any function
Sep 3 2007 CS1301 - O'Hara 11
Writing Simple FunctionsWriting Simple Functions
def nudge():
print “going forward”
forward(1)
print “about to stop”
stop()
nudge()
Indent
Defining functions Creates function Does not
execute/run them Indenting implies
“scope” or code ownership
Call functions from top-level or other functions
No Indention
“Top Level”
Sep 3 2007 CS1301 - O'Hara 12
Writing Simple FunctionsWriting Simple Functionsdef function-name():
statement
statement
…
statement
name()
Sep 3 2007 CS1301 - O'Hara 13
Writing Functions with Parameters
Writing Functions with Parameters
def nudge(speed):
print “Going forward with speed”, speed
forward(speed)
print “About to stop”
stop()
nudge(.2)
nudge(.9)
nudge(1)
Sep 3 2007 CS1301 - O'Hara 14
Octaves of AOctaves of A
def beepA(length, octave):beep(length, 27.5 * (2**octave))
beepA(1,4) # A4beepA(1,1) # A5beepA(3,6) # A6 A4 : 440 Hz
A5: 880 Hz A6: 1760 Hz A7: 3520 Hz
Do I need the parentheses
around 2**octave?
Sep 3 2007 CS1301 - O'Hara 15
Writing Functions with Parameters
Writing Functions with Parameters
def function-name(p1, p2, …, pn):
statement
statement
…
statement
function-name(v1, v2, …, vn)
Sep 3 2007 CS1301 - O'Hara 16
Using Functions that Return Values
Using Functions that Return Values
name = raw_input(“Enter your name”)print “Hello”, name
print “Robot battery voltage”, getBattery()p = takePicture()show(p)
v = abs(-3)print “Absolute value of (-3) =“, v
Sep 3 2007 CS1301 - O'Hara 17
Converting between typesConverting between types
float(3000) # returns 3000.0 int(3.0) # returns 3 int(3.99999) # returns 3 str(3.9) # returns ‘3.9’ int(“3”) # returns ‘3’ int(“3.0”) # error
Sep 3 2007 CS1301 - O'Hara 18
Composing Functions Composing Functions
print abs(int(0 - 3.5))print abs(int(-3.5)) print abs(-3) print 3
show(takePicture())
n = int(raw_input(“Enter a number”))n = int(“9”)
n = 9
Sep 3 2007 CS1301 - O'Hara 19
Writing Functions that Return ValuesWriting Functions that Return Values
def area(radius):
return 3.14 * radius**2
def circumference(diameter):
return 3.14 * diameter
print “Area of a 3 ft circle”, area(3)
print “Circumference”, circumference(2*3)
Sep 3 2007 CS1301 - O'Hara 20
Functions with Local Variables Functions with Local Variables
def area(radius):a = 3.14 * radius**2return a
def circumference(diameter):c = 3.14 * diameterreturn c
print “Area of a 3 ft circle”, area(3)print “Circumference”, circumference(2*3)
Sep 3 2007 CS1301 - O'Hara 21
Variables in a Function are Local
Variables in a Function are Local
Variables in a function are private Including the parameters
Each function has its own variables Even when the names are the same
Allows you to write functions independently without worry about using the same name
Sep 3 2007 CS1301 - O'Hara 22
Different Variables - Same Name
Different Variables - Same Name
def area(radius):a = 3.14 * radius**2return a
def circumference(radius):a = 3.14 * 2 * radiusreturn a
print “Area of a 3 ft circle”, area(3)print “Circumference”, circumference(3)print a
Sep 3 2007 CS1301 - O'Hara 23
Writing Functions with Return Values
Writing Functions with Return Values
def function-name(list-of-params):
statement
statement
…
statement
return value
output = function-name(list-of-params)
Sep 3 2007 CS1301 - O'Hara 24
Passing variables to functionsPassing variables to functions
userinput = raw_input(“Enter a number”)
number = int(userinput)
print “Absolute value = “, abs(number)
Sep 3 2007 CS1301 - O'Hara 25
Calling Your Own FunctionsCalling Your Own Functions
def area(radius):
return 3.14 * radius**2
invalue = raw_input(“Enter the radius”)
r = int(invalue)
Print “Area of a”, r, “ft circle”, area(r)
Sep 3 2007 CS1301 - O'Hara 26
Calling Your Own FunctionsCalling Your Own Functions
def rect_area(length, width):
area = length*width
return area
l = int(raw_input(“Enter the length”))
w = int(raw_input(“Enter the width”))
print “Area of rectangle”, rect_area(l,w)
Sep 3 2007 CS1301 - O'Hara 27
Same Name - Different Variables
Same Name - Different Variables
def rect_area(length, width):
area = length*width
return area
length = int(raw_input(“Enter the length”))
width = int(raw_input(“Enter the width”))
print “Area of rect”, rect_area(length, width)
Sep 3 2007 CS1301 - O'Hara 28
Same Name - Different Variables
Same Name - Different Variables
def rect_area(length, width):area = length*widthlength = 0width = 0return area
length = int(raw_input(“Enter the length”))width = int(raw_input(“Enter the width”)) area = rect_area(length, width)print “The rectangle length =”, lengthprint “The rectangle width =”, widthprint “The rectangle area =”, area
Sep 3 2007 CS1301 - O'Hara 29
Functions in generalFunctions in general
# description of this function
# what it expects as input
# what is provides as output
def function (p0, p2, …, pn):
statement
…
statement
return value
z = function(a0, a2, …, an)
Sep 3 2007 CS1301 - O'Hara 30
Math FunctionsMath Functions
import math math.sin(math.pi) math.log(100)
Math module Set of useful math
functions
Sep 3 2007 CS1301 - O'Hara 31
Where’s the Error?Where’s the Error?
Forgot to return the value!
def avgLight():left = getLight(‘left’)center = getLight(‘center’)right = getLight(‘right’)
avg = (left + center + right) / 3.0
print “Average Light Reading:”, avgLight()
Sep 3 2007 CS1301 - O'Hara 32
Where’s the Error?Where’s the Error?
No Indentation
def avgLight():left = getLight(‘left’)center = getLight(‘center’)right = getLight(‘right’)
avg = (left + center + right) / 3.0return avg
print “Average Light Reading:”, avgLight()
Sep 3 2007 CS1301 - O'Hara 33
Where’s the Error?Where’s the Error?
Not calling function correctly
def avgLight():left = getLight(‘left’)center = getLight(‘center’)right = getLight(‘right’)
avg = (left + center + right) / 3.0return avg
print “Average Light Reading:”, avgLight(1)
Sep 3 2007 CS1301 - O'Hara 34
Where’s the Error?Where’s the Error?
avg is a local variable to the avgLight function
def avgLight():left = getLight(‘left’)center = getLight(‘center’)right = getLight(‘right’)
avg = (left + center + right) / 3.0return avg
avgLight()print “Average Light Reading:”, avg
Sep 3 2007 CS1301 - O'Hara 35
Where’s the Error?Where’s the Error?def avgLight():
left = getLight(‘left’)center = getLight(‘center’)right = getLight(‘right’)
avg = left + center + right / 3.0
return avg
print “Average Light Reading:”, avgLight()
Order of Operations wrong!
Sep 3 2007 CS1301 - O'Hara 36
Where’s the Error?Where’s the Error?def avgLight():
left = getLight(‘left’)center = getLight(‘center’)right = getLight(‘right’)
avg = (left + center + right) / 3
return avg
print “Average Light Reading:”, avgLight()
Integer Division
Sep 3 2007 CS1301 - O'Hara 37
Test on FridayTest on Friday