-1

I am working on a python exercise and here is the question:

Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user.

This is the original list:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

I have the following code:

b = list()
num = raw_input('Give me a number: ')
for i in a:
    if i < num:
        b.append(i)
print b

But no matter what number I entered it always returns all numbers from the original list into the new list.

Any suggestion or comment?

PURWU
  • 397
  • 1
  • 8
  • 22
  • 1
    Because few seem to bother to teach this, I'll try iin this little box. Often in beginning Python it will not be obvious what type object you have in hand. You could look up [raw_input](https://docs.python.org/2/library/functions.html#raw_input) but you won't so here are two friends: `repr()` and `type()`. You've got something in `num` what is it? `print type(num)` will very helpfully tell you it is a `str` while `print type(3)` will tell you you've got an `int`. – msw Mar 16 '16 at 03:38
  • Also, it is pretty important to use meaningful names everywhere, but in this instance, assign the string returned by `raw_input()` to the variable `num` is bound to cause confusion. Contrariwise, `num = int(raw_input())` has far less potential to confuse. – msw Mar 16 '16 at 03:40
  • @msw are you implying the default type of raw_input is string? – PURWU Mar 16 '16 at 03:43
  • 1
    There's no default about it. The manual I linked to says "The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that." `raw_input()` only ever returns a string (except when it raises an `EOFError` exception). Thanks for proving my point about reading the manual. That's sincere, not sarcastic and not about you in particular. – msw Mar 16 '16 at 03:49

1 Answers1

4

You need to cast your input to an int, otherwise you are going to be comparing int to str. Change your input prompt to:

num = int(raw_input('Give me a number: '))
idjaw
  • 25,487
  • 7
  • 64
  • 83
  • Alright. But isn't it going to be a traceback when it's comparison between integer and string?? – PURWU Mar 16 '16 at 02:55
  • @furin_kazan I ran your code by making the adjustment I proposed and it worked. – idjaw Mar 16 '16 at 02:57
  • 1
    @furin_kazan - python 3 gives an Error when you try comparing strings and integer... python2 does not. – MSeifert Mar 16 '16 at 03:06
  • 1
    @furin_kazan (for some reason my comment did not show up..posting again) . Read [this](http://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int) to understand how comparisons between types works. As MSeifert said, in Python 2 you do not get an error when doing this, but the link I provided will provide insight in to this. Python 3 will not let you do this at all. – idjaw Mar 16 '16 at 03:08