Search code examples
while-looppython-2.xraw-input

How to use while loop inside a function?


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


Solution

  • 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]