简体   繁体   中英

For loop that finds min, max, sum and average from a list

I've this assignment in Python 3 where I get a list of numbers and using at least a for loop I need to find the min, max, sum, and average of the numbers. But the tricky part is that I can only use the len() function, no while loops, def/return, max/min, just len() and for loops, can do if/else statements tho. So please let's say this is the list.

numbers=[1,35,54,99,67,2,9]
biggest= numbers[0]
smallest=numbers[0]
for bigs in range(1,len(numbers)):
    if numbers[bigs] > biggest:
        biggest = numbers [bigs]
print("The max number is", biggest)

for smalls in range(1,len(numbers)):
    if numbers[smalls] < smallest:
        smallest = numbers [smalls]
print("The min number is", smallest)

That's what I have for max and min and it does work, a bit messy but it works, but I've no clue how to do sum and average. How could I do all that using only for loops and len()? Thanks!

If you are allowed to store values you could do something like:

smallest = numbers[0]
biggest = numbers[0]
total = 0

for num in numbers:
    if num < smallest:
        smallest = num
    elif num > biggest:
        biggest = num
    total += num

average = total / len(numbers)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM