This is the question:
Write a Python program that reads a positive integer n and finds the
average of all odd numbers between 1 and n. Your program should not
accept a negative value for n.
And here is my code, which curiously doesn’t work:
k = int(input('Enter a positive integer: ')) while k <= 0: print('Please enter a positive integer!! \n') k = int(input('Enter a positive integer: ')) else: b = 1 sum1 = 0 while b <= k: if b % 2 == 1: sum1 = sum1+b b += 1 avg = sum/k print(avg)
Example: input: 8 and output: 2.5, while it should be 4. Any tips?
You have used sum (builtin function name) instead of sum1 (your variable name) in the 2nd last line. Additionally, you need to count the total number of odd numbers and divide using that number instead of the input.