We continue loops today.
- Previously we first defined a specific list first and then looped through the items in the list. We can actually define the list in the loop command itself.
Type and run
for number in [1,2,3]:
print(number, 5number, 10number)
- Type and run
for area in [‘Tejgaon’, ‘Bashundhara’, ‘Shyamoli’]:
print(area)
- We can also use the ‘range’ concept to make a loop go through an ordered sequence of numbers (instead of explicitly defining, let’s say list1=[1,2,3,4,5] )
Type and run
for number in range(5):
print(number, number*2)
4. Note that using range(5) gives you the numbers from 0 to 4. So using range(n) will give you the number from 0 to n-1. What if you want a number range starting from a different value other than zero?
for i in range(3,6):
print(i)
5. Note that range(n1, n2) gives you numbers starting from (including) n1 and ending at n2-1.
Write a code that will print the numbers 1 to 5.
5. We can even specify steps in range. The format is range(start, stop, step).
Type and run
for item in range(1,10,2):
print(item)
6. In the above the program starts from the first number 1 and then hops 2 steps at every iteration until it reaches the end. We can also hop backwards!
for number in range(10, -10, -3):
print(number)
6. Print all the integers between (and including) 195 and 200 but backwards ( I.e., start from 200 and end at 195)