Python Forum

Full Version: Sum up numbers using while(strings)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
a = input()
p = 0
contador = 0
while a != ".":
    a = input()
    contador = contador + 1
if a == ".":
    print(contador)
    print(p + a)
I need to write a program who reads number line by line until ".". It should stop reading at "." and print how many numbers i wrote(contador) and the sum between the numbers. I'm getting this error:
Error:
Traceback (most recent call last): File "C:/Users/Utilizador/AppData/Local/Programs/Python/Python36-32/dffg.py", line 9, in <module> print(p + a) TypeError: unsupported operand type(s) for +: 'int' and 'str'
p and a are of different types. a is returned from the value of input() which always returns a string, and p is defaulted to an int. You cant make a math op from a string and an int.
But i need a string in this case "." to stop the program and print the sum and count of numbers. How do i solve this then?
First, why do you need to print the "."? Second, what is the purpose of "p"?
My teacher said the program had to read numbers line by line until the user writes a stop("."). Then it should print how many numbers you printed(contador) and the sum of all the numbers. p = 0 is a cumulative to have the sum in the end
I don't read that as a requirement to print the ".", if you feel you should, modify your 'print' statement. As to the 'p', where are you modifying its value, as you have it now, 'p' will always equal 0.
Can you make a suggestion then please?
Just as you have a counter for 'contador', you also need to add to 'p' the values entered for 'a'.