I am new to Python and I'm sure that I'm doing something wrong - I would like to ask a user for three numbers and print their sum, here's my current code:
for i in range(0, 3):total = Nonenum = input('Please enter number {}:'.format(str(i)))total += num
By the way, the total = None was to try and declare the variable so I could use it without setting a value?
I get this
Traceback (most recent call last):File "<pyshell#20>", line 4, in <module>total += num
TypeError: unsupported operand type(s) for +=: 'NoneType' and 'str'
You shouldn't do total = None
. NoneType
cannot be used against addition.
There's an extra problem suggested by the error message: From your description you're trying to add 3 numbers, but the return type of the builtin input()
is str
. So this is what you're supposed to write:
total = 0
for i in range(0, 3):num = input('Please enter number {}:'.format(str(i)))total += int(num)
All the points:
- Indent the code correctly. Indentation is a crucial part of Python.
- Don't set
total
to zero at every loop. Only set it once outside the loop
- Take care of types