Search code examples
pythonpython-3.xfor-looptypesinteger

how to loop through a list of integers


I'm trying to loop through a list of integers by using a for loop. However, we know that in python, int is not iterable. So I'm wondering if there's any ways I can store integers in another way so that I can loop through the integers?

def get_index_of_smallest(pint):
    integers_list = []
    for int in pint:
        if int > 0:
            integers_list.append(int)
    return min(integers_list)
 
integers = int(input("Please enter a bunch of integers: "))
get_index_of_smallest(integers)

The code above is what I'm trying to attempt. You see that if I try to pass a list of integers into a for loop, python returns with an error and saying the data type "int" is not iterable.


Solution

  • There seems to be a few things you may want to fix in your code:

    1. Do not use int as variable name. It has a special meaning in Python and this name should never be used in other ways.
    2. If you expect user to input a bunch of numbers you cannot directly cast input to int. It depends on how the numbers will be inputed but you first need to separate them from input string (initially input returns strings). That's what's causing your error. Look at the previous answers for examples.
    3. The logic of your function could use some improvement. If you want to return smallest, non-negative element from your list there is no need to first filter them to separate list.