The Sum Numbers Program

This is an example mini-program.

The aim is to ask the user for a series of numbers. If the user enters 0, the program then outputs the sum of the inputted numbers

Feel free to play around with the program as much as you like.

The first program uses a break to exit the while loop. Notice that the while condition is always True. So the break is essential to exit.

# The Sum Numbers Program
print("Welcome to The Sum Number Program")
total = 0

while True:
  input_string = input("Please enter a number. Enter 0 to stop\n")
  if input_string == "0":
    break
  
  x = float(input_string)
  total += x  # note this is shorthand for: total = total + x

print(f"Sum of numbers entered is {total}")

We can also do this without a break by using a bool named program_over. You will notice that this is a little more verbose.

print("Welcome to The Sum Number Program")
program_over = False
total = 0

while not program_over:
  input_string = input("Please enter a number. Enter 0 to stop\n")
  if input_string == "0":
    program_over = True
  else:  
    x = float(input_string)
    total += x

print(f"Sum of numbers entered is {total}")

NOTE: Please avoid using break if you can. It can lead to code that becomes hard to reason about or follow.

While this might seem irrelavant to this program, imagine a much larger program with a more complicated flow and the use of lots of breaks and continues. This can become hard to reason about.