introduction to computer science – chapter 4 csc 2010 spring 2011 marco valero
TRANSCRIPT
Introduction to Computer Science – Chapter 4CSc 2010Spring 2011Marco Valero
Overview
• Sensory definitions
• Randomness
• Asking questions
• General while loop
• Conditions
• Sensing functions
• If statement
Sensory Definitions
•External sensors - exteroceptors
▫Sight, sound
▫IR sensors, camera
•Internal sensors - interoceptors
▫Position of self, pain
▫time, stall, battery level
Randomness
• Random numbers are useful
▫Real life has randomness
▫ from random import *
• random()
▫Returns a value between 0.0 and 1.0
• randint(A, B)
▫Returns a value between A and B
Asking Questions
• Graphically presents the user with a question
askQuestion(“Do you like tacos?”)
• Returns the value of the button label
• Override the amount of buttons and default
labels with a list
askQuestion(“What is your favorite taco”,
[“Lengua”, “Tripa”, “Pastor”, “Carnita”])
Time
•timeRemaining(<duration>)
•wait(<count>)
•currentTime()
▫Returns the number of seconds elapsed
since some predefined time
Moving Forward
forward(1.0, 3.0)
forward(1.0)wait(3.0)stop()
while timeRemaining(3.0):forward(1.0)
stop()
General While Loops
startTime = currentTime()while (currentTime() – startTime) < 3.0:
forward(1.0)stop()
while <some condition is true>:<do something>
Conditions
• Expressions that evaluate to True or False
• Comparison (relational) operators
▫< less than
▫> greater than
▫<= less than or equal
▫>= greater than or equal
▫== equal
▫ != not equal
Conditions
• Examples
▫42 > 23
• Logical (boolean) operations
▫and, or, not
• Examples
▫ (6 > 7) or (3 > 2)
▫ (a == “hello”) and (count > 1)
23 == 23 “Hello” < “hello”
Boolean Algebra
• (A or True) will always be True
• (not (not A)) will just be A
• (A or (B and C)) is the same as ((A or B) and (A or C)
• (A and (B or C)) is the same as ((A and B) or (A and C))
• (not (A or B)) is the same as ((not A) and (not B))
• (not (A and B)) is the same as ((not A) or (not B))
Sensing Functions
• getStall()
▫ Returns True if the robot has stalled, False otherwise
• getBattery()
▫ Returns current voltage being supplied by battery
while not getStall():
forward(1.0)
stop()
speak(“Muhaha! I meant to do that!”)
If statements
if <condition>:<do something>
if a < 5:print “Buy more Doritos”
if not tired:print “Play more video games”
If-Else Statement
if <condition>:<do something>
else:<do something>
if tired:goToSleep()
else:cleanKitchen()