Finding something in a list
To search is to look for an item that matches a question. You might search a player list for a name or an inventory for a key. A simple method checks the items one at a time.
This method is called linear search. You do not need to sort the list before using it.
Look along a bookshelf
Suppose the books on a shelf are not in any particular order. To find a title, you can read each label from left to right. If none matches, you reach the end without finding it.
A program needs to remember both possibilities: “found” and “not found.” Otherwise it might accidentally treat the first item as a successful result even when the wanted item is absent.
Search some pretend player names
# language: en
let players = ["Pip", "Nova", "Milo"]
let wanted = "Nova"
let found = false
for player in players:
if player == wanted:
set found = true
if found:
say "Player found."
else:
say "Player not found."
found starts false. A matching name changes it to true. The result message comes after the loop. This version keeps checking the remaining items after finding a match; it is simple and sufficient for a small list.
Predict, then run
Which message should appear for "Nova"?
Player found.
Now predict what happens for "Luna", which is absent. Also consider an empty list: no comparisons run, so found keeps its initial false value.
Your challenge
Search a list of backpack items for "key". Then add the key twice. Does the result change? Our program answers “Does at least one exist?” It does not count matches or report their positions.
A common mistake
Putting set found = false in an else inside the loop can erase an earlier match when the next item does not match. Only a match should change this example’s flag. Text comparison also distinguishes "Nova" from "nova"; this program does not ignore letter case.
