[Tutor] optional else with while

Alan Gauld alan.gauld at yahoo.co.uk
Sun Oct 11 14:11:17 EDT 2020


On 11/10/2020 18:07, Manprit Singh wrote:

> to understand how an optional else clause works with  while loop  .
> 
> n = int(input("Enter any number"))
> initial = n//2
> while initial > 1:
>     if n % initial == 0:
>         print("Greatest factor of",n,"is",initial)
>         break
>     initial -= 1
> else:
>     print("It is a prime number")


I'd say that's a pretty fair demonstration of a while/else.
Mostly you don't need it since the code will just continue
after the loop, but in cases like this where you want to
do something only if the while exits "normally" (ie no breaks)
the else clause is the right choice.

-- 
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