Python For Else Method

A for else statement in Python is a loop that executes a block of code for each item in an iterable object, and then executes another block of code if the loop finishes normally without encountering a break statement.

For example, you can use a for else statement to search for a person with a certain name in a list of people, and print a message if no such person is found:

people = [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 22}, {'name': 'Peter', 'age': 30}, {'name': 'Jenifer', 'age': 28}]

for person in people:
    if person['name'] == 'Alice':
        print('Found Alice!')
        break
else:
    print('Alice not found.') 

for x in range(9):
  print(x)
else:
  print("Finally finished!")

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions