Home > Back-end >  Stopping a loop based on conditions
Stopping a loop based on conditions

Time:10-09

So I have a program that is supposed to calculate a running total. The user sets the maximum and then enters numbers between 1 and the maximum. If the user enters a negative number it's supposed to stop the loop and give the running total. I'm having an issue where it outputs the total and then continues to ask me for the next number. It also adds the negative number to the total which I don't want. I'm very new to python and any insight is greatly appreciated.

END = int(input('Enter a maximum value:'))
total = 0
correct = False
while True:
    number = int(input('Enter a number between 1 and the maximum:'))
    total = total   number
    if number <= -1:
        print('Sum of all valid numbers entered:', total)
        correct = False
    elif number < 0 or number > END:
        print('Invalid number')

So I made some changes. I'm a little more confused. The code certainly stops at the point its supposed to but now it only returns the negative number entered.

END = int(input('Enter a maximum value:'))
total = 0
correct = False
while True:
    number = int(input('Enter a number between 1 and the maximum:'))
    if number <= -1:
        total = total   number
        print('Sum of all valid numbers entered:', total)
        correct = False
        break
    elif number < 0 or number > END:
        print('Invalid number')

CodePudding user response:

If you want to stop a while loop you have to use the break statement. So it will look like this

     total = total   number
     correct = False
     break
    elif

CodePudding user response:

You can use break to stop any loop without using any additional variables:

while True:
    number = int(input('Enter a number between 1 and the maximum:'))
    total = total   number
    if number <= -1:
        print('Sum of all valid numbers entered:', total)
        break
    elif number < 0 or number > END:
        print('Invalid number')

And going on the code should be:

END = int(input('Enter a maximum value:'))
total = 0
while True:
    number = int(input('Enter a number between 1 and the maximum:'))
    if number <= -1:
        print('Sum of all valid numbers entered:', total)
        break
    elif number > END:
        print('Invalid number')
    else: # if the number is bigger than or equal 1
        total  = number # total = total   number
  • Related