The break statement

The break statements are used to change the flow of any block of statements. There might be a situation where we might need to break the loop in between; in that scenario, using the break statement will help us achieve our goal. Let's have a look:

attraction_in_Vienna = ['Stephen plaz', 'Maria-Hilfer strasse', 'Donau-insel', 'Vienna-Philharmonic']
first = "Donau-insel"
for each in attraction_in_Vienna:
if(each == first):
break
print each

Here we have created a list of attractions available in the city of Vienna. We take a variable first and assign it a value as "Donau-insel":

We want to print all the places of attraction in Vienna. But there is a twist. We would like to stop the moment Donau-insel occurs in the list. Hence, for every iteration of the for loop, the if block will check each and every element inside the list and compare it with the value we have given to compare, that is, "Donau-insel". So the program will print all the names appearing before Donau-insel, and the moment Donau-insel occurs, the break statement terminates the loop. There can be several situations where the break statement can be handy such as searching for a keyword in a stack of words, searching a palindrome, and so on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.30.62