[Tutor] loop questions

Mitya Sirenef msirenef at lightbird.net
Sun Apr 7 00:23:05 CEST 2013


On 04/06/2013 06:00 PM, 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))
 >
 >
 > 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)
 > _______________________________________________
 > Tutor maillist  -  Tutor at python.org
 > To unsubscribe or change subscription options:
 > http://mail.python.org/mailman/listinfo/tutor
 >


In pseudocode, you need to do something like this:

- loop forever
     inp = user input
     if inp is Quit: break
     try to convert inp to int
     if success:
         print if inp is leap year or not
     else:
         print error


I have written a small function that handles a more general case of
asking user for a certain kind of input (e.g. number, text, yes/no, etc)
and keeps asking it until the answer in right format is given. Here it
is:

import re

def simpleinp(pattern, prompt="> ", convert=None, errmsg="Invalid 
Input", blank=False):
     """Keep asking user for input until it matches `pattern`."""
     if pattern == "%d": pattern = "\d+"; convert = int
     if pattern == "%s": pattern = ".+"

     while True:
         i = input(prompt).strip()
         if blank and not i: return None

         if re.match('^'+pattern+'$', i):
             return convert(i) if convert and i else i
         else:
             print(errmsg)

# print( simpleinp("%d", "integer: ") )
# print( simpleinp("%s", "string: ") )
# print( simpleinp(".*", "string or blank: ") )
# print( simpleinp("[ynYN]", "y/n: ") )


HTH, -m


-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/

True friends stab you in the front.
Oscar Wilde



More information about the Tutor mailing list