Professional Documents
Culture Documents
ENGR 101.week 4
ENGR 101.week 4
Introduction to
Programming
Week 4
Simple Repetition
for i in range(4):
print ‘Hello’
• Use a for loop to draw the square.
for loop – syntax
for i in range(4):
fd(bob,100)
lt(bob)
wait_for_user()
Exercises
square(bob)
Encapsulation
• Encapsulation?
• Wrapping a piece of code up in a function
• Benefits?
• The same motivation to use any function!
• You re-use the code. It is more concise to call a
function twice than to copy and paste the body!
• Easy maintenance: Just need to modify the function
definition. Function calls will directly be affected by
the modification.
Encapsulation
# encapsulation demo
ray = Turtle()
square(ray)
Ex 2
square(bob, 100)
Generalization
• Generalization?
• Adding a new parameter to a function
• Benefits?
• It makes the function more general:
• in the previous version, the square is always
the same size;
• in this version, it can be any size.
Generalization
Next step: instead of drawing squares, draw regular
polygons with any number of sides.
>>> type(True)
<type 'bool'>
>>> type(False)
<type 'bool'>
Relational Operators
• Relational operators are:
x == y # x is equal to y
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
• Another example:
# implementation
def countdown(n):
while n > 0:
print n
n = n-1
print 'Blastoff'
The while statement