4.1 Search for Alice
Write a program that asks the user for a name. Search through an array of names and display all the positions where that name appears.
names = ["Alice", "Bob", "Eve", "Alice", "Tom", "Alice"]
Enter a name to search for: Alice Found at position 0 Found at position 3 Found at position 5
SET names TO ["Alice", "Bob", "Eve", "Alice", "Tom", "Alice"]
INPUT target
FOR i FROM 0 TO LENGTH(names) - 1
IF names[i] = target THEN
OUTPUT "Found at position", i
END IF
END FOR
names = ["Alice", "Bob", "Eve", "Alice", "Tom", "Alice"]
target = input("Enter a name to search for: ")
for i in range(len(names)):
if names[i] == target:
print("Found at position", i)
# An array of names to search through
names = ["Alice", "Bob", "Eve", "Alice", "Tom", "Alice"]
# Ask the user for the name they want to search for
target = input("Enter a name to search for: ")
# Go through the entire array, one position at a time
for i in range(len(names)):
# Compare the current name at position i with the target
if names[i] == target:
# If they match, display the position
print("Found at position", i)
Extension
Ask the user for:
- a target name to search for, and
- a new name to replace it with.
Search through the entire array and replace every occurrence of the target with the new name.
Show the array before and after, and display how many replacements were made.
If there are no matches, say “Not found” and leave the array unchanged.
Before: ['Alice', 'Bob', 'Eve', 'Alice', 'Tom', 'Alice'] Enter the name to replace: Alice Enter the new name: Zara Replaced 3 occurrence(s) of 'Alice' with 'Zara' After: ['Zara', 'Bob', 'Eve', 'Zara', 'Tom', 'Zara']