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) # 100To 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) # 140The 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) # 145To 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
EasyA shop wants the total in its cash register at the end of the day. The program reads two lines:
- The sales of the day, whole numbers separated by spaces. The line is empty when there were no sales.
- 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: 800Try 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler