When is else used at the same level as the for / while repetition statement?

Asked 1 years ago, Updated 1 years ago, 87 views

for i in range(10):
    print(i)

    if i == 9:
        print("Too big - I'm giving up!")
        break;
else:
    print("Completed successfully")

I don't know why you use else when you have a code like this.

At first, I thought the else statement would be executed if the for statement didn't even start (if False

After executing it, if you erase break, else will be executed, and if break is not cleared, else will not be executed.

When should the for-else statement be used?

python for-else if문 for-loop

2022-09-22 10:42

1 Answers

When you use a for-else statement, you usually say, "Look for an item in an item in your earlobe. But if you can't find anything, it means...

found_obj = None
for obj in objects:
    if obj.key == search_key:
        found_obj = obj
        If break #item is found, break - else statement will not be executed
else:
    print 'No object found.' #Running only if item is not found

If you encapsulate it and write it as a function,

def find_obj(search_key):
    for obj in objects:
        if obj.key == search_key:
            return obj

Or if you use the built-in list,

matching_objs = [o for o in objects if o.key == search_key]
if matching_objs:
    print 'Found', matching_objs[0]
else:
    print 'No object found.'


2022-09-22 10:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.