How are all the inputs stored? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How are all the inputs stored?

This python code adds all the numbers a user enters when after they type stop. I’m confused on how they’re stored if the only variable is x. Can someone break this down for me? sum = 0 while True: x = input() if x == "stop": break sum += int(x) print(sum)

13th Sep 2021, 8:25 PM
Cplou
Cplou - avatar
3 Answers
+ 4
The variable has a specific memory area where a number is kept until it is overwritten in a new while loop. But before this happens it is added to the sum.
13th Sep 2021, 8:34 PM
JaScript
JaScript - avatar
+ 3
Cplou , you may have overlooked the variable sum. here some comments how it works: sum = 0 # initialize a variable that will hold the running total while True: # the loop is running until the input is "stop" x = input() # we take a number as input, but keep it as string data type if x == "stop": # if input is "stop"... break # ... the loop will be left sum += int(x) # the current input number will be converted to integer dara type and added to variable sum. it is the same as: sum = sum + int(x) print(sum) # after leaving the loop, the content of the variable sum will be printed you can see the numbers that have been input are not stored themselves, as they are processed in the running total, also called the cumulative sum.
14th Sep 2021, 7:00 PM
Lothar
Lothar - avatar
0
With print(id(x)) you get the storage address of x. Try this: x = 3 print(id(x)) x = 'auto' print(id(x))
14th Sep 2021, 4:25 AM
Paul
Paul - avatar