Learning outcomes
By the end of this lecture, you should be able to:- write basic
forloops withrange - iterate over strings/lists directly
- compare
forandwhileusage
Syntax
First examples
0 1 2 3 4
for vs while
Use for when:
- number of iterations is known
- iterating over sequence elements
while when:
- loop depends on dynamic condition
- iterations are unknown in advance
range quick forms
range(stop)->0tostop-1range(start, stop)->starttostop-1range(start, stop, step)-> controlled step
Dry run
2 4 6
Exam hints and traps
range(1, 5)does not include5- negative step requires descending boundaries
- variable updates automatically in
for
Practice
- Print numbers 1 to 10 using
for. - Print characters of
"code"one per line. - Predict output:
Answers
5 3 1
