For Loop
Loops are so core for any programming language. Python is no exception here. Let’s check how to use it and what functionality loops provide. Simple scenario, how to print numbers from 0 to 10?
for i in range(11):
print(i)
As simple as could be, but let’s walk through details. First to start with is a range. It’s actually a special sequence type that generates a sequence of integers. In this particular case it generates a sequence, from 0 to 10, 11 is an upper cap for the sequence and not included. By default the first element is 0 (similar to indexes of characters in a string. But you can use another versions of range function, e.g. range(5, 10) – sequence starts from 5 inclusive, and ends on 9, 10 is not included. You can even make more cooler things, by providing 3rd parameter to the range: range(0, 10, 2) – 2 in this case is a step, in this particular example the generated sequence would be 0,2,4,6,8. You can even set a step to negative and generate decrementing sequence, range(10,-1,-1) – sequence would be from 10 to 0 including, since we stop at -1. Ranges are very powerful and widely used.
Let’s move on and try to figure out the whole statement at line 1. Basically we initialize variable i with 0 and increment it by one until it is less than 11. Then we use it in a print statement on line 2.
The last, but not least to highlight. Python use indentation, to specify boundaries of the loop, basically 4 spaces in this case. Let’s see another sample:
for i in range(10): # outer loop
print("In the outer loop") # printed 10 times, part of outer loop
for j in range(10): # inner loop, part of the first
print(i * j) # will be printed 100 times
print("End of outer loop") # printed 10 times
print("End of program") # printed only once, not part of loop
The code above will generate results of multiplication of numbers from 0 to 9 time 0 to 9.
For loop could be also applied to strings:
for c in "Hello world!":
print(c)
The snippet above will print each letter of the sting on a separate line, since it will iterate it one by one and store in a variable c on each run.
While Loop
Similar to for loop, you can use a while:
x = 0 # initialize x with 0
while x < 10: # begin loop, and on each iteration check that x is less than 10
print(x) # print x
x += 1 # increment x by 1, short form here, equivalent to x = x + 1
logic is similar, but initialization of the counter x condition check x < 10 and increment x += 1 is done in separate lines. Based on a problem you are solving, might be more convenient. Important to notice, if the last line is removed, program will stuck in a loop forever, since x is 0 and it value remains the same on each iteration. It’s important to keep in mind, while using while loops.
Follow up questions:
- write a code that prints results of multiplication of each number from 0 to 10 using
whileloops - write a code, that generates the following output:
*
**
***
****
*****
Leave a comment