[Tutor] Module Review
Alan Gauld
alan.gauld at yahoo.co.uk
Wed Apr 12 20:11:28 EDT 2023
On 12/04/2023 17:48, Thurman Hill wrote:
> Fill in the blanks to print the even numbers from 2 to 12.
>
> number = range(2,12+1,2) # Initialize the variable
Notice that in Python 3 range returns a range object.
So number is a range object
> while number > 0: # Complete the while loop condition
Now you are comparing a range object to a number.
Thats not a valid comparison so Python objects.
> print(number, end=" ")
> number # Increment the variable
I have no idea how you think that works or what it does.
> # Should print 2 4 6 8 10 12
You don't need a while loop a for loop over the range
will do it just fine
> while number > 0: # Complete the while loop condition
> TypeError: '>' not supported between instances of 'range' and 'int'
As I explained above - number is a range object.
You can't compare it to a number.
Incidentally even if your code had resulted in a series of
numbers, which I think is what you expected, none of them
would be less than 0 so your loop would never have ended...
A tip for the future: when you hit a problem in Python
that you don't understand use print statements to see
what you variables look like. In this case a
print(number)
Would have should that it was not in fact a number but a range object.
Also try things out in the interactive prompt:
>>> range(2,12+1,2)
Would also have shown that you got a range object
>>> list(range(2,12+1,2))
[2,4,6,8,10,12]
Would show the content of the list version.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list