2

I decide to modify the following while loop and use it inside a function so that the loop can take any value instead of 6.

i = 0
numbers = []
while i < 6:
    numbers.append(i)
    i += 1

I created the following script so that I can use the variable(or more specifically argument ) instead of 6 .

def numbers(limit):
    i = 0
    numbers = []
    
    while i < limit:
        numbers.append(i)
        i = i + 1
    print numbers
user_limit = raw_input("Give me a limit ")      
numbers(user_limit)

When I didn't use the raw_input() and simply put the arguments from the script it was working fine but now when I run it(in Microsoft Powershell) a cursor blinks continuously after the question in raw_input() is asked. Then i have to hit CTRL + C to abort it. Maybe the function is not getting called after raw_input().

Now it is giving a memory error like in the pic. enter image description here

5
  • 1
    did you press enter after the input? Commented Jan 12, 2014 at 11:33
  • If you upgraded to Python 3.x then you would have had an error You should consider whether you really need to run such an ancient version of Python. Commented Jan 12, 2014 at 11:40
  • 1
    You are doing an infinite loop, see answer belows. Your i<limit test always returns True because limit is a string Commented Jan 12, 2014 at 11:40
  • @Duncan I am following a book and now it works Commented Jan 12, 2014 at 11:43
  • Of course, your numbers function duplicates the built-in range function. Commented Jan 12, 2014 at 11:59

1 Answer 1

10

You need to convert user_limit to Int:

raw_input() return value is str and the statement is using i which is int

def numbers(limit):
    i = 0
    numbers = []

    while i < limit:
        numbers.append(i)
        i = i + 1
    print numbers

user_limit = int(raw_input("Give me a limit "))
numbers(user_limit)

Output:

Give me a limit 8
[0, 1, 2, 3, 4, 5, 6, 7]
Sign up to request clarification or add additional context in comments.

3 Comments

Cf CPython manual : CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address. integer are always "lesser than" string. Test : 1<'1'
@Raphaël Braud yes you are right, that's why it's an endless loop.
and that's why it gave me a memory error. Thanks! now it's working fine!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.