Explaining For/Else In Python

In response to a thread on G+ I've decided to write a this article on 'how for/else works'.

I should start by saying that this isn't intuitive or simple. It's quite complicated, but it has a very clear use case. Let me start by stating as simply as I can the use-case.

for element in seq:
    if somecondition(element):

I think that example is reasonably clear, but it's important to explain what's happening here.

If a 'for' loop does not break, it's else is run, otherwise the else is not run. So:

  • The else suite is run if:
    • the sequence is empty
    • break is never executed
  • The else suite is bypassed if:
    • break is executed
    • a return statement in the loop is executed
    • an exception raises in the for loop

I hope that's clear. Any comments or addendums or errors I've made, please let me know in the comments.

Edit: I don't think using an 'else:' on a for loop is a bad idea. But I think it should only be used in exactly the idiom presented in the example, anything with more complicated flow control or more than 8 lines should be re-factored to use a function call with 'return' in the appropriate places.


Anonymous said...

The example works but it would probably be more useful to describe why this is extremely bad style and should be avoided, wouldn't it?

geoffrey said...

It should be a syntax error to use else: without a comment on the line saying "WARNING: else doesn't mean what you probably think it does."

Marien Zwart said...

Is this language feature really disliked this much? I use it a lot and it does exactly what I think it does: if the end of the loop ("for" and "while" both support this) is reached without hitting "break", the "else" clause runs. Which is useful for finding an interesting element and doing something else (like complaining) if it's missing.

What's tripping people up? Are you expecting the "else" to only run if the loop body never executed?

Courtney M. Tapia said...

College authority need to a best college paper writing service provider person. You can all time communication with your nearest college. If you think you are the perfect on this position.

Freya said...

Discover English idiomatic expression and phrases with complete meaning, sample examples and origin facts, arranged in very simple cataloging structure like search and alphabetically listing, idioms.in makes it easier to find your idiom.

Joshua dollar said...

We are a team of assignment experts; I got lot of information from your blog. You have done amazing job! . Online Homework Help.

ahmed said...

Ideal Corner Pest Control Co. in Dammam has many and many services provided to its valued customers offering the best service of insect control for all types of insects, rodents and reptiles.
شركة مكافحة حشرات
شركة مكافحة النمل الابيض بالخبر
شركة مكافحة حشرات بالخبر
شركة رش مبيدات بالخبر

Bella said...

This Is Really Great Work. Thank You For Sharing Such A Useful Information Here In The Blog.
pay someone to do assignment
write my essay
Assignment Help
<a href="https://liveassignmenthelp.com/>Assignment Help</a>



Ideal Assignment Help said...

Ideal Assignment Help mainly focuses on offering you the best of the services regarding Assignment Help at the most reasonable price. Our IdealAssignmentHelp nursing assignment help Experts help to complete your assignment within a given deadline. Nursing is an important part of health care sector and it requires the students to develop a cultural competence along with the knowledge of professionalism.

Best Furnace Repair said...

Thanks for keeping people up on what's happening.

Best Furnace Repair

Andy Alvin said...

Avail the best marks and spencer case study answers, Accounting homework helper and Shell SWOT analysis at MyAssignmentHelp. We are a wide range of experts available 24*7 to assist students around the globe.

Online Assignment Help said...

Do you wonder how to write a dissertation methodology sample that supports you in moving forward with your writing? Well, you don’t have to! You have MyAssignmenthelp.com that offers you the most professional dissertation writing services at all academic levels.

Unknown said...

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

Law assignment help

Science assignment help

Biotechnology assignment help

Economics Homework help

Computer science assignment help

Isabell Kiral said...

We will discuss here about Python which is an interpreted, high-level, general-purpose programming language. This language is created by Guido van Rossum. You know, Python's design philosophy emphasizes code readability with its notable use of significant white space. I hope, you will understand it. Dissertation writing services.

bellastenberg said...

Hello everybody! Welcome to our page with the best essay in the world! We have employed trained specialists so that our customers can get professional assistance with different types of assignments anytime. Our experts are able to complete any writing projects punctually whatever the imposed time frame is.

James Ian said...

My friend promised to buy me a cup of coffee for referring him to your site. Thank you for coffee. Kindly keep updating us on new articles. These days, the most common pump for a shallow well is a jet pump. Jet pumps get mounted above the well, either in the home or in a good house, and draw the water up from the well through suction. Visit Shallow Well Jet Pump with Pressure Tank for more.

assignmentauthors said...

The regulation of the amount of deposits and or reserves by the central bank is what that determines the interest’s rates. content writing services

Selectmytutor said...

Those students who are searching for Online Tutors in UK can contact with our experts. We are best services providers over the country. Our experts are available round the clock, students can contact them at any time.

Mark Rangel said...

College application essay stressful? Get effective assistance with your college application essay! We have a decent college entrance sample essays which will help you to write your essay on your own.

James Ian said...

Thank you for bringing to a halt my long search topic. I really benefited from your content. If you are experiencing trouble striking a balance between your busy academic life and handling your online classes, you can get help from a professional who will take online classes on your behalf. It doesn’t matter the kind of help you need, whether it is passing your exam, finishing your assignments or even the entire classwork, you can get help here at Online Class Help .

Selectmytutor said...

Those students who are searching for Online Tutors in UK can contact with our experts. We are best services providers over the country. Our experts are available round the clock, students can contact them at any time.

Nionica said...

Hi, this is a nice blog thanks for sharing the informative blog. Myassignmenthelp.com provide the Nestle swot analysis for an assist to student queries. Our writers conduct thorough research to provides you with a flawless Nestle swot analysis . My Assignment help brings write my essay paper. Writing an elaborate write my essay paper is anything but easy and most students lack the tenacity to work on the details accurately. If you get more details Please visit the site through Link.

Silvia said...

Hello there, great stuff you’ve shared here I will be checking regularly for more articles. But wait! When it becomes hard to manage your online assignment, availing Online Assignment Help is the best choice. Many students often fail to submit their assignment before deadlines and end up scoring low grades because they didn’t have enough time to write the assignment given on time and satisfactorily. Visit Assignment Help . for assistance.

meldaresearch said...

Online logistics management writing services are very difficult to complete and many students are always searching for Logistics Writing Services Online to help them complete their logistics coursework writing services and logistic research paper services.

MyAssignmentHelp said...

We offer impressive 4P of marketing assignment help right here at MyAssignmentHelp.com. Dump all your woes with our team of super-fast experts, and you can have assignments delivered urgently – as and when you need them!

Unknown said...

Such a wonderful information blog post on this topic allassignmentservices.com provides assignment service at affordable cost in a wide range of subject areas for all grade levels, we are already trusted by thousands of students who struggle to write their academic papers and also by those students who simply want assignment maker to save their time and make life easy.

KIm larry said...

Great Stuff men
i am sharing a
bibliography creator
so stronggly suggestion use this tool

essay help zone said...

Essay Help Zone

Why Academic Essay Writing is so Necessary for Student

How Professional Essay Writing Services Can Help Students

What are the Different Types of Writing

Expert Essay Writers

Professional Essay Writing Services

Online Essay Help

Max Russell said...

Thank you so much for sharing this excellent information. I am glad to discover your post. We are the Best Mobile app development company. Visit Website: Kotlin Application Development Company USA

Andrew Robert said...

We are no 1 assignment writing service provider in the world and especially in Australia. Please connect with us: Phone: +61-2 9191 7405, E-mail: sales@no1assignmenthelp.com, Website: assignment help, Office: Level 4/22 Harry Chan Avenue, Darwin City NT 0800, Australia

Brian Symbian said...

Please click the link : https:// cdrreport.net/ to get CDR report. We are the best choice for the CDR Report Generation. We are the top CDR Report generator. If you are worried about how to write your CDR, Just call us.We will solve it in minutes. Contact: Email-briansymbian25@gmail.com, Tel:- +61-2 9191 7405, Address:- 37 Bligh Street, Sydney, NSW 2000, Australia
CDR Report

yanmaneee said...

jordan 4
steph curry shoes
golden goose outlet
curry shoes
supreme outlet
air jordan
kd shoes
paul george shoes
lebron james shoes

Antony Christ said...
This comment has been removed by the author.
Antony Christ said...

It was nice to read your blog. If anyone needs case study Samples then visit to our website:- Case Study Samples . We provide all type of case study assignments for MBA, Nursing, Laws and Engineering students.

wadleighmacdonnell said...

Casinos Near Casinos Near Casinos Near Casinos - Mapyro
Looking for a 경주 출장안마 quiet 시흥 출장샵 place to stay? Mapyro 영주 출장샵 places you in the right direction with a clear 목포 출장샵 location for you to find your favorite slot. 양산 출장마사지

Zanaib said...

Strategy is the core for any organization. It helps in making a centralized decision, and a sure way to understand and resolve a problem. However, this is not just random principles, but specific goals, decisions, and objectives to face the challenges. Cybersecurity Architect Career Overview

steahet said...

her comment is here gucci replica her latest blog Valentino Dolabuy blog here dolabuy gucci

teti said...

replica bags turkey next page v6o87d5n60 replica bags canada click for info f7x26h3s21 replica bags china replica bags nyc why not try this out u6y44e5t53 high replica bags replica bags prada

cloud machine learning services said...

Organize AI/ML at scale to mechanize analytics, improve customer experiences, predict outcomes, and recognize patterns