break

Loops are very helpful for iterating over an object or just repeating some part of the code. Yet, sometimes it’s necessary to “break” out of the loop prematurely. Imagine if you want to find the first negative element in the sequence. If you start iterating from the first element of the sequence and go further, you would want to stop the loop as soon as you find a negative element and not continue looping as it’s redundant. This can be achieved with a break command:
numbers = [
	1, 5, 100, 77, 
	2, -7, 8, 10, 
	14, 67, -8, 0,
]
for n in numbers:
	print(f'Trying {n}...')
	if n < 0:
		print(f'Found a negative number: {n}')
		break

print('Done!')
The outputs of the program will be the following:
Trying 1...
Trying 5...
Trying 100...
Trying 77...
Trying 2...
Trying -7...
Found a negative number: -7
Done!
The program stops as soon as it reaches a negative number.
 

Challenge

You are searching for the records of Mike in a big pile of documents. You look at each document one by one and try to see whose records are they. If you find Mike in the records, you would like to print the number of documents you’ve looked at before seeing the one for Mike.
The input contains names - each name on a single line.
The output of the program should be: Found Mike's records after looking through X documents. Where X is the number of documents you’ve looked at so far.
Input
Kate
Bob
Mike
Anna
Steven

Output
Found Mike's records after looking through 3 documents
 
To check your solution you need to sign in
Sign in to continue