my code basically asks people for their age. I need to get the average of ages and then the minimum and higher number between the answers given, but I don't know how to do that last part. I triend using (min(x)) but I keep getting this error code: TypeError: 'int' object is not iterable
Any help would be appreciated.
students= int(input('How many students are there in the class? '))
preguntas= int(input("A number lower than " str(students) ": "))
i=0
totalAge=0
# MAIN CICLE
if questions<students:
while i<questions:
age= int(input("What's your age?"))
totalAge =age
i= i 1
average= age/i
print ("The age average is " str(average) "")
CodePudding user response:
So as it seems that you are getting multiple inputs from the user (different ages) and you want to get the max and min from those ages.
So what you are doing wrong is you are providing only one input (x) to the min function which is wrong as min or max function is expecting an iterable (list, tuple, set etc) which has multiple elements and will give you minimum or maximum out of that.
So while getting input from the user, save that in some list;
lst = []
age = int(input("Enter your age:"))
lst.append(age)
Then after getting all the inputs;
maximum_age = max(lst)
minimum_age = min(lst)
In nutshell, this is the full solution;
lst = []
# running a loop just to get multiple inputs
for i in range(5):
age = int(input("enter the age: "))
# storing the input in the list lst
lst.append(age)
# print average value
print(sum(lst)/len(lst))
# print maximum age
print(max(lst))
# print minimum age
print(min(lst))
CodePudding user response:
You're getting the error TypeError: 'int' object is not iterable
because the thing you are passing into x when you did (min(x))
is an integer and not an iterable (like a list).
That is, doing min(3)
does not make sense since, if you are trying to find the minimum of some values, it wouldn't make sense to pass just one value (i.e. the integer you are passing with x
).
Instead, if you have a list like mylist = [9, 2, 5, 13]
, then you can do min(mylist)
which will give you the value 2
. This won't result in an error since a list is an iterable since you can iterate through it, unlike a sole integer which you can't iterate over.