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?
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.'
623 Uncaught (inpromise) Error on Electron: An object could not be cloned
576 Who developed the "avformat-59.dll" that comes with FFmpeg?
922 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
573 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
© 2024 OneMinuteCode. All rights reserved.