user1730308
user1730308

Reputation: 191

Python list iteration with for loop

I'm trying to input numbers, and I want my function to return the smallest number.

However, my code seems to stop executing early: as soon as one number in the input is less than the other.

a = input("")
smallest = 0
a = a.split(" ")
numbers = a

def smallestindex(numbers):
    for i in range(len(numbers)):
        b = int(numbers[i])
        smallest = int(numbers[0])
        print(b)
        if b < smallest:
            smallest = b
            return smallest

print (smallestindex(numbers))

Upvotes: 1

Views: 154

Answers (3)

John La Rooy
John La Rooy

Reputation: 304137

If you wish to return the index of the smallest number as the function's name suggests, you would need to change your code to something like this

def smallestindex(numbers):
    numbers = [int(x) for x in numbers] # convert numbers to list of ints
    smallest_idx = 0
    smallest = numbers[0]
    for i, b  in enumerate(numbers):
        if b < smallest:
            smallest_idx = i
            smallest = b
    return smallest_idx

Upvotes: 0

schesis
schesis

Reputation: 59118

You have an indentation error: you're returning smallest inside the for loop, so executution stops on the first iteration through the loop where the if condition is met. You need to return your result after the loop has completed. Also, you're resetting smallest each time through the loop, so your if block won't do what you intend. Here's a fixed version:

def smallestindex(numbers):
    smallest = int(numbers[0])
    for i in range(len(numbers)):
        b = int(numbers[i])
        print(b)
        if b < smallest:
            smallest = b
    return smallest

Upvotes: 1

Blckknght
Blckknght

Reputation: 104702

This is an indentation issue. Currently your return statement happens whenever the if b < smallest block gets run. That's probably not what you had intended. You need to unindent that to be at the same level as your for statement, so that it runs after the loop ends, not in the middle.

You also need to move the line where you initialize smallest to the top of your function, rather than having it happen on each cycle of the loop. Here's how that should look:

def smallestindex(numbers):
    smallest = int(numbers[0])    # moved this line up
    for i in range(len(numbers)):
        b = int(numbers[i])
        print(b)
        if b < smallest:
            smallest = b
    return smallest   # unindented this line

It's also worth noting that you loop could be done slightly differently. Rather than looping over the indexes of the list (using range(len(numbers))), you can loop over the list items directly using for b in numbers.

Upvotes: 4

Related Questions