So , many of you don't know that there is a 'else' statement in for loop basically in python.
I know python is a amazing programming language and it has some amazing features too. So, today we will be learning about the 'else' keyword
sometime you would have to search a friend name from a list of dictionary, like:
so at this point we can use a FOR loop for searching my friend
in this case we will use a user input.
So, now if user types friends name like: 'sadi'
it will search the whole dictionary
then it will print "friend found" in the console.
at this moment if the user type a wrong name which is not in the list of dictionary like,
enter your friends name: 'showmik'
it will give you nothing in the console.
so in this case we can use the else keyword.
so, if we write the code like this,
this time if the user type wrong name which is not in the list. it will print 'friend not found' in the terminal
But there is a problem using else keyword!
and that is,
now if the user type correct write name which matches the list, it will output something like this,
because the 'else' will be run after the loop ends. that's why it is printing the statement what the 'else' provide.
i.e, 'friend not found'
in this case we can use 'break' statement after the loop ends. it will false the else keyword
like,
in this time after user type the correct name , the only thing will be print is 'Friend found'
for the 'break' statement the 'else' keyword will not be printed.
source: Tofayel
Top comments (0)