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()}")
>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}")