[Tutor] Odds and even exercise

Steven D'Aprano steve at pearwood.info
Sat Mar 27 14:25:49 CET 2010


On Sat, 27 Mar 2010 11:55:01 pm TJ Dack wrote:
> Hi, just started python at Uni and think i am in for a rough ride
> with zero prior experience in programming.
> Anyway my problem that i can't fix my self after googling.
>
> The exercise is to generate a list of odd numbers between 1-100 and
> the same for even numbers.
>
> So far this is what i haveCODE: SELECT
> ALL<http://python-forum.org/pythonforum/viewtopic.php?f=3&t=17610#>#A
> way to display numbers 1 - 100
> numbers = range(100)
> #A way to display all odd numbers
> odd = numbers[::2]
> #A way to display all even numbers

Nice try! Sadly you *just* missed getting it though. Here's an example, 
using 1-10 instead of 1-100:

>>> numbers = range(10)
>>> odd = numbers[::2]
>>> print numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print odd
[0, 2, 4, 6, 8]

So you have two small errors: you have the numbers 0-99 instead of 
1-100, and consequently the list you called "odd" is actually even. 
This is what programmers call an "off by one" error. Don't worry, even 
the best programmers make them!

The first thing to remember is that Python's range function works on 
a "half-open" interval. That is, it includes the starting value, but 
excludes the ending value. Also, range defaults to a starting value of 
0, but you need a starting value of 1. So you need:

numbers = range(1, 101)  # gives [1, 2, 3, ... 99, 100]

Now your odd list will work:

odd = numbers[::2]  # gives [1, 3, 5, ... 99]

How to get even numbers? Consider:

Position: 0, 1, 2, 3, 4, 5, ...  # Python starts counting at zero
Number:   1, 2, 3, 4, 5, 6, ...  # The values of list "numbers"
Odd/Even: O, E, O, E, O, E, ...

Every second number is even, just like for the odd numbers, but instead 
of starting at position zero you need to start at position one. Do you 
know how to do that?

Hint: numbers[::2] means:

start at 0, finish at the end of the list, and return every 2nd value.

You want:

start at 1, finish at the end of the list, and return every 2nd value.



> I can't find a way to easily list the even numbers, i really need a
> easier way to find answers my self but using the help docs in idle
> didn't get me far, any tips that you guys have when you come across
> something you can't solve?

So far you seem to be doing well: think about the problem, google it, 
think about it some more, ask for help.

Also, try solving the problem with pencil and paper first, then repeat 
what you did using Python.

Finally, experiment! Open up the Python interpreter, and try things. See 
what they do. See if you can predict what they will do before you do 
them. For example, what would these give?

range(1, 101, 3)
range(2, 101, 4)

Try it yourself and see if you predicted correctly.



-- 
Steven D'Aprano


More information about the Tutor mailing list