Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Write a Python program that reads a positive integer n and finds the average of all odd numbers between 1 and n

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading