Search code examples
pythonpython-3.xfor-loopuser-input

How to use a for loop with input function


I simply have to make a sum of three numbers and calculate the average

import sys
sums=0.0
k=3
for w in range(k):
    sums = sums + input("Pleas input number " + str(w+1) + " ")
print("the media is " + str(sums/k) + " and the Sum is " + str(sums))

And the error :

Pleas input number 1 1
Traceback (most recent call last):
  File "/home/user/Python/sec001.py", line 5, in <module>
    sums = sums + input("Pleas input number " + str(w+1) + " ");
TypeError: unsupported operand type(s) for +: 'float' and 'str'

Solution

  • The input() function returns a string(str) and Python does not convert it to float/integer automatically. All you need to do is to convert it.

    import sys;
    sums=0.0;
    k=3;
    for w in range(k):
        sums = sums + float(input("Pleas input number " + str(w+1) + " "));
    print("the media is " + str(sums/k) + " and the Sum is " + str(sums));
    

    If you want to make it even better, you can use try/except to deal with invalid inputs. Also, import sys is not needed and you should avoid using semicolon.

    sums=0.0
    k=3
    for w in range(k):
        try:
            sums = sums + float(input("Pleas input number " + str(w+1) + " "))
        except ValueError:
            print("Invalid Input")
    print("the media is " + str(sums/k) + " and the Sum is " + str(sums))