Python Forum

Full Version: Simple Code - What's going on inside it?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Below is code from my class. When I run the code with several integers, it somehow stores them and returns them all when "else" is run. I suspect it is because of the empty "" values for the variables below. Is this correct? Also, I don't completely understand how this works below: num_final = num_temp + num_1; and num_temp=num_final; Is this telling the code-gremlin to store the values in memory until "else" is called?





num_1="" 
num_temp="" 
num_final="" 

while True:
    num_1 = input ("Enter and integer: ")
    if num_1.isdigit():
        num_final = num_temp + num_1
        num_temp=num_final
    else:
        print(num_final)
        break
 
You get a long string of concatenated integers because of the line:
num_final = num_temp + num_1
Here you operate with strings, and + operator with strings means concatenation. You can play with that in Python console to see how it works. If code should be summing the integers instead, conversion from string to integer is required with int().

Quote:num_final = num_temp + num_1; and num_temp=num_final;
Without num_temp=num_final each loop would start with empty num_final string and all you would get in the end is the last number you enter. You can check the working easily by commenting out lines and printing values you want to observe.
thank you. Will play with it also.