for loop and range() function
for loop basics
The for
loop is used to repeat a block of code a certain number of times:
for var in sequence: # for-loop header, always end with ':'
code to run in the loop # Standard Indention! 4 spaces!
code to run in the loop
...
code to run outside of the loop
...
The for..in
statement is a looping statement which iterates over a sequence of objects
, i.e. goes through each item in the sequence.
Sequence
There are several types of sequences in Python. Strings, lists, and tuples are the most commonly used. A sequence is essentially just an ordered collection of items. We will learn more about these sequences in later chapters.
Loop through a string sequence
let's use a string
to demo how for
loop works, please type in:
for letter in 'Buzz':
print(letter)
for
loop starts with the keywords for ... in ...
, and always ends with a colon. The beginning of the next line is indented 4 spaces, which tells the computer that the second statement is part of the for
loop.
In the above example, letter
is a variable that holds a single character of string Buzz
in each iteration. for
goes through the string sequence starting with the first element 'B'
to the last 'z'
. Run the code to see each letter is printed out in the console like this:
B
u
z
z
Python's indentation rule
One of the most distinctive features of Python is its use of indentation to mark blocks of code. the block of code in the the for
loop example is indented four spaces, which is typical amount of indentation for Python.
range() function
Python built-in range( )
function comes handy in generating integers in a sequence.
Let's type in an example:
for i in range(5):
print(i)
Click run and check results in the console:
0
1
2
3
4
We can see that range(5)
generates integers from 0 to 4, the number 5
is not included.
This for
loop repeats 5 times. In each loop, variable i
receives a different value from 0
to 4
that's generated by range(5)
. These numbers (0, 1, 2, 3, 4)
are printed out in the console.
You can try printing out integers from 0
to 10
.
Answer:
for t in range(11):
print(t)