CodeBlanks Logo Icon CodeBlanks

Search function

Add linear_search to the project and look up a target grade.

Print the result

Now we add report_result(notes, target). This function calls find_note and prints the result to the screen.

If the target is found, its index is printed; if not, 'not found' is printed. This gives clear feedback to the user.

User feedback

A good search tool should clearly report the result to the user. The found index is printed; when absent, a 'not found' message is shown.

This approach makes it clear at a glance whether the search succeeded. The user is never left in ambiguity.

Practice Print result

Write report_result(notes, target). Print index if found, 'not found' otherwise. Call report_result(init_notes(), 92) to print 3.

Starter code

solution.py
def init_notes():
    # Return note array
    return [85, 90, 78, 92, 88]
def find_note(notes, target):
    # Search for target
    for i in range(len(notes)):
        if notes[i] == target:
            return i
    return -1
def report_result(notes, target):
    # Print result

Sample solution

solution.py
def init_notes():
    # Return note array
    return [85, 90, 78, 92, 88]
def find_note(notes, target):
    # Search for target
    for i in range(len(notes)):
        if notes[i] == target:
            return i
    return -1
def report_result(notes, target):
    # Print result
    idx = find_note(notes, target)
    if idx >= 0:
        print(idx)
    else:
        print('yok')
report_result(init_notes(), 92)

Expected output

3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Result check

Question
if idx ____ 0, the target was found.
Answer
if idx >= 0, the target was found.

Explanation: >= is right.

2 Search function: match the terms

Term Meaning
report_result Print
find_note Search
idx Index
not found Absent

3 What does report_result do?

  • Defines array
  • Searches and prints Correct answer
  • Sorts array
  • Deletes target

Explanation: report_result searches and prints the result.

All lessons in Beginner