if it wasn’t for the range…


So, let’s combine some of what we’ve learnt from the past few tutorials.  Let’s say we wanted to print all the even numbers from 0 to 20.  We know how to get these numbers by using range(21), but this gives us all the numbers from 0 to 20.  We just want the even ones.

Even numbers are those which have a remainder of 0 when you divide them by two.  Python has  a special operator (called %) which does just this:

>>> 1%4
1
>>> 2%4
2
>>> 3%4
3
>>> 4%4
0
>>> 5%4
1

So for example: 1%4 means “what is the remainder when you divide 1 by 4” (it’s 1).   To test whether a number is even we can see whether this remainder is 0 when the number is divided by 2:

>>> 1%2
1
>>> 2%2
0
>>> 3%2
1
>>> 4%2
0

One is odd, two is even etc.

So to print the even numbers from 0 to 20 we:

get the numbers from 0 to 20 from  a range statement

we use a “for” loop to run over each of the numbers in that range

for each of those numbers we test to see if it is even – and if it is

print the number:

>>> for i in range(21):
...   if i%2 == 0:
...      print i
...
0
2
4
6
8
10
12
14
16
18
20

Please notice that there are three levels of indentation here.  That’s significant because each indicates a code block which relates to the previous statement.

Now try to print out the numbers divisible by 10 between 0 and 100.

And then try to print out the numbers in the sequence 5, 15, 25… up to 95.  This is harder, but you can do it with what’s on this page.

Later we’ll learn that you can do much of this with just range() alone, but that’s for another day.

7 Responses to if it wasn’t for the range…

  1. Pingback: Consolidation: CryptoPyThy « Python Tutorials for Kids 8+

  2. Pingback: Making this Code Your Own « Python Tutorials for Kids 8+

  3. ion says:

    >>> for i in range(100):
    if i%5== 0:
    print i

    0
    5
    10
    15
    20
    25
    30
    35
    40
    45
    50
    55
    60
    65
    70
    75
    80
    85
    90
    95
    >>> for i in range(100):
    if i%5== 0:
    if i%10 != 0:
    print i

    5
    15
    25
    35
    45
    55
    65
    75
    85
    95

  4. Rona says:

    >>> for i in range(100):
    if i%5 ==0 and i%10 ==5:
    print i

    5
    15
    25
    35
    45
    55
    65
    75
    85
    95
    >>> for i in range(100):
    if i%5 == 0 and not i%10 ==0:
    print i

    5
    15
    25
    35
    45
    55
    65
    75
    85
    95
    >>>

  5. lokeyokeyee says:

    this is a good progamming tool

Leave a reply to lokeyokeyee Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.