Home > Mobile >  having trouble using min and max for my loop : 'int' object is not iterable [closed]
having trouble using min and max for my loop : 'int' object is not iterable [closed]

Time:10-09

I cannot figure it out how to find the minimum values of the number inputed user how`

sum = 0
x = 0
counter = 0
minumum = 0
while x >= 0:
 counter = counter   1
 x = int(input('enter a postive number:'))
 if x >= 0:
 sum = sum   x
 minumum = min(x)
 avg = sum/counter
print(sum)
print(avg)
print(minumum)

CodePudding user response:

You need to give min() something to compare against. Otherwise, Python assumes you're passing it an iterable with multiple objects that it needs to find the smallest value from.

Try min(x, minimum)

Additionally, it might be worth doing some more searching for existing answers before adding a new question. This existing thread turned up from a quick search. (See this meta discussion on what is the expected effort for new questions)

CodePudding user response:

The problem (besides the many problems with your code) is that at each iteration of the while loop you try to update the minimum variable to whatever the value of min(x) is.

The min() function is not supposed to be used the way you did. Instead, it expects an array (an iterable in fact) of values and returns the minimum value in that array. For instance, min([2, 3, 4, 1, 5]) would return 1.

What you should do is this:

if x < minimum:
    minimum = x

The problem is that you initialized minimum to 0. This means that if the values of x are 2, 3, 4, 1, 5, then the minimum would remain 0 instead of 1. To solve this, you could initialize minimum to None and inside the while loop you could do:

if minimum == None:
    minimum = x
elif x < minimum:
    minimum = x

CodePudding user response:

Just check if the counter variable is zero or not; if it's true, then initiate the minimum with the first input. In the following steps, update this value by using min function between two successive input values.

sum = 0
condition = True
counter = 0
minimum = -1
while condition:
  x = int(input('enter a postive number:'))
  if x >= 0 :
    if counter == 0 :
      minimum = x
    else :
      minimum = min(x, minimum)
    counter = counter   1
    sum = sum   x
  else :
    condition = False

avg = sum/counter
print(sum)
print(avg)
print(minimum)
  • Related