Alex Nugent
Alex Nugent

Reputation: 11

TypeError: 'int' object is not iterable and don't know why

So I'm new to programming and was doing a code which was to find the smallest value of 10 int(input()). My code it as follows:

x, y = 0, 0 

while x < 10:
    n = int(input())
    y += n
    x += 1
print(y)

s = min(y)
print(s)

However the problem I am having is for the like s = min(y) it gives me TypeError: 'int' object is not iterable. How do I go about fixing this?

Upvotes: 0

Views: 2149

Answers (2)

queeg
queeg

Reputation: 9374

If you expect min(5) -> 5 then you got the minimum number of one number - python does not do that.

What you can do is get the minimum of a list of numbers, such as min([5,2]) -> 2. And therefore you should at least write

s = min([y])

where s would actually come up with the value of y.

Upvotes: 0

Samwise
Samwise

Reputation: 71424

Adding an int to another int gives you a single int, not a list of two ints. min expects an iterable (e.g. a list) so it'll error if you just give it an int.

Do:

x, y = 0, []

while x < 10:
    n = int(input())
    y.append(n)
    x += 1
print(y)

Now y is a list[int], and you can take the min of it:

s = min(y)
print(s)

You can also create y more easily with a simple list comprehension and a range:

y = [int(input()) for _ in range(10)]
print(min(y))

Upvotes: 3

Related Questions