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

Taking a series of inputs and calculating the minimum, maximum, total and average but stopping once a negative number is inputted

When i enter a negative number it doesn’t stop my while loop and instead keeps asking for inputs. List works fine and gets the correct values

def positive_statistics():
    total = 0
    count = 0
    a = []
    while True:
        number = float(input("Input a positive Number:"))
        if number < 0:
            break
        a.append(number)
        total = total + number
        count = count + 1
    a.sort()
    maximum = a.pop()
    minimum = a.pop(0)
    average = total / count
    return minimum, maximum, total, average

expected it to stop asking for inputs when a number < 0 is entered

Input a positive Number:4
Input a positive Number:8
Input a positive Number:3
Input a positive Number:-1
Input a positive Number:-1
Traceback (most recent call last):
  File "C:\Users\helka\eclipse\ws\helk0000_l07\src\t05.py", line 17, in <module>
    print(f"{positive_statistics()}")
             ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\helka\eclipse\ws\helk0000_l07\src\functions.py", line 77, in positive_statistics
    maximum = a.pop()
              ^^^^^^^
IndexError: pop from empty list
from functions import positive_statistics
positive_statistics()
print(f"{positive_statistics()}")

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

>Solution :

So, you’ve called the function once and then discarded that information, then called it again to print it. This explains the symptoms you’re seeing.

You correctly read in 4, 8, and 3 in the first call, and -1 terminates the loop. The second time you call the function you immediately give it -1, which means the list inside the function is empty, and trying to pop from it gives you an exception.

Instead call the function and store the results.

from functions import positive_statistics

result = positive_statistics()
print(f"{results}")
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