Python Forum

Full Version: Question: While
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This is the code:

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

while True:
    num_1 = input("Enter an integer: ")
    if num_1.isdigit():
        num_final = num_temp + num_1
        num_temp = num_final
    else:
        print(num_final)
        break
and this is the output after I input 3 and then 4:
Output:
Enter an integer: 3 Enter an integer: 4
What I don't understand is why the second output is not seven in accordance with num_temp = num_final. Why code doesn't have memory on previous entry?
Seems to pretty much work. You need to type some non-digit input so that the else runs:
num_final = ""
 
while True:
    num_1 = input("Enter an integer (type 'q' to quit): ")
    if num_1.isdigit():
        num_final += num_1
    else:
        print(num_final)
        break
Output:
Enter an integer (type 'q' to quit): 3 Enter an integer (type 'q' to quit): 7 Enter an integer (type 'q' to quit): 23 Enter an integer (type 'q' to quit): 5 Enter an integer (type 'q' to quit): q 37235
What I mean is why it doesn't add, in your case 3+7=10, why the outcome is not 310? And why did you remove num_temp = num_final line?
Quote:
while True:
    num_1 = input("Enter an integer: ")
    if num_1.isdigit():
        num_final = num_temp + num_1
input() returns a string. num_1 is still a string at the point you add. You are just concatenating strings, not adding ints. You need to convert both to an int to do that.
You never did any string to int conversion so 3 + 7 will never = 10.
"3" + "7" = "37".

If what you want is "3" + "7" = "310" then you can do that (but I have no clue why you want to).
You need to accurately explain your input and desired output and how it differs from what you are getting.
I erased num_temp in your code because it didn't do anything.