I’m trying to write a Python program using numpy, which prints the average/mean of all the even numbers bigger than 10 which are also between a specific lower and upper bound input by the user. So, if the user inputs 8 as the lower number and 16 as the upper number, then the output would be 14, but I can’t seem to get it.
This is what I tried so far.
import numpy as np lower = int(float(input('Waiting for input: '))) upper = int(float(input('Waiting for input: '))) def sum_even(a, b): count = 0 for i in range(a, b, 1): if(i % 2 == 0): count += i return count print(f"{function1(lower, upper):.2f}")
But it’s not giving me the average.
Advertisement
Answer
Your function is just adding all of the even numbers between the lower and upper bound (excluding the upper bound because of how the range function works).
So when you input 8 and 16, you’re computing 8+10+12+14=44.
You need to keep track of how many evens there are in the function and then divide the sum by that value, as such:
import numpy as np lower = int(float(input('Waiting for input: '))) upper = int(float(input('Waiting for input: '))) def mean_even(a, b): count = 0 sums = 0 for i in range(a, b+1, 1): if(i % 2 == 0) & (i>10): count += 1 sums += i return sums/count print(f"{mean_even(lower, upper):.2f}")
Then, using your example inputs:
>> Waiting for input: 8 >> Waiting for input: 16 14.00