Python Forum

Full Version: Infinite loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
# [ ] use a "forever" while loop to get user input of integers to add to sum,
# until a non-digit is entered, then break the loop and print sum
sum = 0

the best I was able to think up doesn't work
while True:
    sum = ''
	sum1 = input("add number: ")
	if sum1.isdigit():
	    sum = sum + sum1
	else:
	    break
		print(sum)
Suggestions are welcome.
untested:
while True:
    sum = 0
    sum1 = input("add number or 'Q' to quit: ")
    if sum1 == 'Q':
        break;
    if sum1.isdigit():
        sum = sum + int(sum1)
    else:
        print('Please enter a digit!')
Below sum = sum + int(sum1) I added print(sum) but it's printing only the last input, not the sum. Not sure why.
show new code
just to mention that sum is a built-in function and should not be used as variable name - as is your code now you overwrite sum and the built-in function is no longer available
(Jan-19-2018, 12:14 PM)buran Wrote: [ -> ]just to mention that sum is a built-in function and should not be used as variable name - as is your code now you overwrite sum and the built-in function is no longer available

Here are all the built-in functions: https://docs.python.org/3/library/functions.html
Look at them.
(Jan-19-2018, 12:02 AM)Larz60+ Wrote: [ -> ]show new code

while True:
    suma = 0
    sum1 = input("add number or 'Q' to quit: ")
    if sum1 == 'Q':
        break;
    if sum1.isdigit():
        suma = suma + int(sum1)
        
    else:
        print('Please enter a digit!')
New it just repeats input request.
Each time the code is repeated in the loop, suma gets set to 0. You will need to put suma = 0 outside of while loop.

Sure it prints only input request. There is no print statement in the "if" that would print anything, until next loop iteration.
suma = 0
while True:
    
    sum1 = input("add number or 'Q' to quit: ")
    if sum1 == 'Q':
        break;
    if sum1.isdigit():
        suma = suma + int(sum1)
        print(suma)
         
    else:
        print('Please enter a digit!')
This code works as I wanted!
Glad you did it, and thanks for posting solution!