You are on page 1of 2

Repetition_For

Ibrahim Abou-Faycal

#
EECE-231
#
Introduction to Computation & Programming with Applications
#
Repetition - for Structure

Reading: [Guttag, Chapter 3] Material in these slides is based on


• Slides of EECE-230C & EECE-230 MSFEA, AUB
• [Guttag, Chapter 3]

0.1 For loop


The syntax of a counter-controlled while loop:
[ ]: start = 1
stop = 2
step = 1
variable = start
while variable < stop:
# code block
variable = variable + step
# Here step > 0

A simpler structure is through the for-loop syntax:


[ ]: for variable in range(start,stop,step):
#code block
pass

• Can skip step: default value of step is 1

1
[ ]: for variable in range(start,stop):
#code block
pass

Thus, variable takes the values: start, start+1, · · ·, stop-1


• Can also skip start: default value of start is 0
• step can be also negative, e.g., for step=-1, the variable takes the values: start, start-1, · · ·,
stop+1
[ ]: for i in range(5):
print(i, end=' ')

print('\n')

for i in range(2, 5):


print(i, end=' ')

You might also like