[Tutor] Using break, else with for loop
Alan Gauld
alan.gauld at yahoo.co.uk
Sun Oct 11 03:58:08 EDT 2020
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
More information about the Tutor
mailing list