Running Totals

A running total is the act of looping a number of times, each time updating a total of a value. The core component of a running total is that typically, the total is set before the loop begins and inside the loop the total is updated.

Both fixed loops and conditional loops can be used to create a running total. Each type of loop has its benefits and negatives.

Key Points

Running totals update a value inside of a loop.

The total should be assigned before the loop starts.

Both fixed loops and conditional loops can be used.

 

What does a Running Total look like?

As a running total can be used in both a fixed loop and a conditional loop, it is important to understand why each loop would be used.

A fixed loop should be used when the total will be updated a set number of times, regardless of what the total is.

A conditional loop should be used when the total has an impact, for instance, when the total gets over 100 or reaches 0.

Here are two examples.

In this example, the total will always increase 10 times, so we can loop 10 times.

  1. Set the total to 0
  2. Loop 10 times
    1. Each loop, increase the total by another value

The value that the total is increased by could be from an input, a calculation or a set value. Further logic could be added to make the total more complex, but it will still repeat 10 times.

This is how it might look in code.

total = 0

for i in range(10):
    number = int(input("What would you like to increase the total by? "))
    total = total + number

In this example, the loop will repeat until the total is greater than 25

  1. Set the total to 0
  2. Repeat until total is greater than 25
    1. Each loop, increase the total by another value

The value that the total is increased by could be from an input, a calculation or a set value. Further logic could be added to make the total more complex, but it will stop looping when the total is greater than 25.

This is an example of how this might look.

total = 0

while total <= 25:
    number = int(input("What would you like to increase the total by? "))
    total = total + number

National 5 Requirements

You should be able to implement a running total into your code to solve a problem.