+ 1

What’s wrong with my code?

You’re making a calculator that should add multiple numbers taken from input and output the result. The number of inputs is variable and should stop when the user enters "stop". Sample Input 4 32 6 stop Sample Output 42 Use an infinite loop to take user input and break it if the input equals "stop". sum=0 n=1 while True: x=input() if int(x)>0: x += sum else: break n+=1 print (sum) I’m getting a “cannot concatenate str and int” error.

20th Sep 2021, 4:52 PM
Steele Jackson
Steele Jackson - avatar
5 Respuestas
+ 4
change line 4: x=input() # to x = int(input()) input() returns a string, so even if you enter 5. It will register that as the string "5". And you can't add a number and a string.
20th Sep 2021, 4:57 PM
Slick
Slick - avatar
+ 3
Steele Jackson , this is your code re-arranged and slightly modified: total=0 # variable is for running total / sum, but should not be named 'sum' as this is builtin function while True: x=input() # input has to be taken in string, not in integer, as we have to handle the 'stop' input << Slick if x == "stop": # first we check for 'stop' break # in this case we leave the loop else: total += int(x) # running total will be handled print (total) # finally we print the total
20th Sep 2021, 8:08 PM
Lothar
Lothar - avatar
+ 2
sum is int (integer, means number) input() is str (string, means some text) convert string to number with int() method. x = int(x) Apart from syntax error, there is a logic error. Instead of incrementing input by sum, you should increment the sum by input. sum += int(x)
20th Sep 2021, 4:58 PM
Gordon
Gordon - avatar
+ 2
Steele Jackson , on the left side of an assignment we can not have any functionality. it just gets assigned the result of the expression being on the right side total += int(x) is identical with: total = total + int(x)
21st Sep 2021, 11:24 AM
Lothar
Lothar - avatar
+ 1
Lothar thank you for the individual line explanations. One more thing - why does total += int(x) work, and int(x) += total not work? Wouldn’t the program be adding int(x) to the running total, and not the other way around?
21st Sep 2021, 10:49 AM
Steele Jackson
Steele Jackson - avatar