[Tutor] loop questions

Alan Gauld alan.gauld at btinternet.com
Sun Apr 7 10:24:10 CEST 2013


On 06/04/13 23:00, Soliman, Yasmin wrote:
> I have two questions on these simple programs:
>
> 1st why does this loop keep repeating after I enter 'Quit'?
>
> import calendar
> m = raw_input(“Enter a year: “)
> while m != “Quit”:
>   if calendar.isleap(int(m)):
>    print “%d is a leap year” % (int(m))
>   else:
>    print “%d is not a leap year” % (int(m))
>

I don't understand why it even starts repeating since
the only user input is before the loop. However you
need to enter exactly "Quit" and not QUIT or quit
or any other combination... It usually better to
force the user input to upper or lower case, eg:

while m.lower() != "quit":

> 2nd  How can I make this program not crash when a user enters a non integer?
>
> m = raw_input(“Enter an integer: “)
> while not m.isdigit():
>   m = raw_input(“Enter an integer: “)
>   num = int(m)

Moving the last line out of the loop will help.
But there are other things to check in addition to isdigit().
That's why Python tends towards exception handling rather
than pre-validation.

eg.

while True:
    try: m = int(raw_input(....))
    except ValueError,TypeError: continue

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list