+ 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)
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.
+ 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.
0
With print(id(x)) you get the storage address of x.
Try this:
x = 3
print(id(x))
x = 'auto'
print(id(x))