Python Forum
Beginner: Code not work when longer list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Beginner: Code not work when longer list (/thread-40013.html)



Beginner: Code not work when longer list - raiviscoding - May-19-2023

Hello,

I been watching videos from python for everyone and there was this code.

numlist = list()
while True:
    inp = input("Enter a number:")
    if inp == 'done' : break
    value = float(inp)
    numlist.append(value)
avarage=sum(numlist) / len(numlist)
print('Avarage: ', avarage)
It runs fine for while and then it would give this error at some points when entering new number:

Error:
Traceback (most recent call last): File "c:\Users\...\Desktop\PYton\numlist.py", line 5, in <module> value = float(inp) ^^^^^^^^^^ ValueError: could not convert string to float: ''
Just wondering why that happens.
Thanks for help.
Raivis.


RE: Beginner: Code not work when longer list - buran - May-19-2023

(May-19-2023, 08:14 AM)raiviscoding Wrote: Just wondering why that happens.
It's not because of the list length, but because there is empty string '' and it cannot convert that to float. Obviously you just hit Enter at some point.


RE: Beginner: Code not work when longer list - deanhystad - May-19-2023

Instead of checking for "done", check if len(inp) == 0 or if inp == "". Now you just print <Enter> without entering a number to exit.

Or you could exit on any non-number input.
numbers = list()
try:
    while True:
        numbers.append(float(input("Enter a number:")))
except ValueError:  # Raised by float(str) when str is not a numeric string.
    print(f"Average{numbers} = {sum(numbers) / len(numbers)}")