[Tutor] Using break, else with for loop

Manprit Singh manpritsinghece at gmail.com
Sun Oct 11 04:07:57 EDT 2020


Dear sir ,

The point I want to raise here is , in my program I am using break because
I want my program 's for loop to break at a point where an odd number is
found .
But in your code  you are checking the entire list .
Need your comments

Regards
Manprit Singh

On Sun, Oct 11, 2020 at 1:30 PM Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 11/10/2020 07:38, Manprit Singh wrote:
> > Dear sir ,
> >
> > Consider a problem where I have to check if a list contains an odd
> number.
>
> > l = [2, 4, 6, 5, 8, 3]
> > for i in l:
> >     if i % 2 != 0:
> >         print("Odd number found in list")
> >         break
> > else:
> >     print("List does not contain odd number")
>
> That's a valid solution.
> A slightly shorter version is:
>
> if any(n%2 for n in l):
>    print("Odd no found in list")
>
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list