Home > Software design >  Create a function in Python that has as input a forloop
Create a function in Python that has as input a forloop

Time:12-19

I’m trying to define a function that takes as input 8 different values using a forloop and returns the average the minimum and the maximum of the inputs that have been inserted. What am I doing wrong?

I tried in this way: enter image description here

def x(u): for i in range(8): c=float(input()) y=0 values=[] values.append(c) avg=(y c)/8 return avg, ("The maximum is {:.0f}".format(max(values))),("The minimum is {:.0f}".format(min(values))) print(x(1))

Edit: thanks you for your suggestions,I tried with your code but it gives me this error: int' object is not callable

Here is the new code:

 def function():
  values = []
  for i in range(8):  
      x=(float(input()))
      values.append(x)
  mean = float(sum(values)/len(values))
  return mean, max(values), min(values)
    
 print(function())
TypeError      Traceback (most recent call last)
<ipython-input-245-dbc2112cdcc7> in <module>
      8   return mean, max(values), min(values)
      9 
---> 10 print(function())

<ipython-input-245-dbc2112cdcc7> in function()
      5       x=(float(input()))
      6       values.append(x)
----> 7   mean = float(sum(values)/len(values))
      8   return mean, max(values), min(values)
      9 

TypeError: 'int' object is not callable

CodePudding user response:

def func():
    values = []
    for i in range(8):  
        values.append(float(input()))
    return (avg(values)/len(values), max(values), min(values))
        

CodePudding user response:

At every iteration of the for loop you replace the value in "c" with a new value and in the end you only have the last number you typed. You also have a variable "u" you don't even use.

def x():
    values = []
    for i in range(8):
        values.append(float(input()))
    avg = sum(values)/len(values)
    return avg, max(values), min(values)

print(x())
  • Related