Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Question: While
#1
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?
Reply
#2
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
Reply
#3
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?
Reply
#4
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.
Recommended Tutorials:
Reply
#5
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020