Menu
CoddyTech

Summing Values

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 49 of 78.

GDScript has no built-in function that adds up an array. You add the values with a loop and a running total, a variable that starts at 0 and grows by each value:

var coins := [12, 30, 8, 50]
var total := 0
for amount in coins:
	total += amount
print(total) # 100

To add the values to a starting amount, start the total there. A player who had 40 coins before the level ends with 140:

var total := 40
for amount in coins:
	total += amount
print(total) # 140

The same loop adds up a dictionary when it goes over values(), and adds up one field of every dictionary in an array when it reads that field:

var inventory := {"potion": 3, "arrow": 20, "bomb": 2}
var items := 0
for count in inventory.values():
	items += count
print(items) # 25

var party := [{"hero": "Mia", "hp": 80}, {"hero": "Leo", "hp": 65}]
var party_hp := 0
for member in party:
	party_hp += member["hp"]
print(party_hp) # 145

To get one total per group, keep the totals in a dictionary. get() with the default 0 covers a group that has no total yet:

var loot := [["gold", 10], ["gems", 2], ["gold", 25]]
var totals := {}
for drop in loot:
	totals[drop[0]] = totals.get(drop[0], 0) + drop[1]
print(totals) # { "gold": 35, "gems": 2 }

For an average, divide the total by the number of values, and convert to float first so the decimals stay: float(total) / coins.size().

challenge icon

Challenge

Easy

A shop wants the total in its cash register at the end of the day. The program reads two lines:

  1. The sales of the day, whole numbers separated by spaces. The line is empty when there were no sales.
  2. The cash that was in the register at the start of the day (a whole number).

Add every sale to the starting cash and print the result after Total: . For the inputs 100 200 150 300 and 50, the output is:

Total: 800

Try it yourself

extends Node

func _ready():
	var sales := OS.read_string_from_stdin().split(" ", false)
	var starting_cash := int(OS.read_string_from_stdin())
	# Add every sale to the starting cash and print the total
	pass
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler