[Tutor] How to check if user input is an integer

Mitya Sirenef msirenef at lightbird.net
Fri Mar 29 14:46:52 CET 2013


On 03/29/2013 07:33 AM, Ghadir Ghasemi wrote:
> Hi guys I am trying to create  part of a vending machine. The section below is if the user wants to 
insert 50p coins. It works but when I entered a non integer like 
'dfsdf', the program just broke. Is there a way that the program can 
check if the input is an integer, and if it is, then the program does 
all the calculations, but if it isn't the program just keeps asking for 
an input? Thanks. Here is the section.
 >
 > fiftypencecoins = int(input("how many 50p coins do you want to insert 
or press 'e' to exit : "))
 > if fiftypencecoins == 'e':
 >         break
 > else:
 >      currentmoney += fiftypencecoins * 5/10
 >      print("your newly updated credit is £" + str(currentmoney) + "0")
 > _______________________________________________
 >


I've recently made a couple of functions that do this in a more general
way. There are some usage examples at the end, including y/n input. The
difference between them is that the 2nd function adds more options.



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)


def getinp(pattern, prompt="> ", convert=None, errmsg="Invalid Input", 
ignorecase=False, lower=False, blank=True):
     """Keep asking user for input until it matches `pattern`."""
     if pattern == "%d":
         pattern = "\d+"
         convert = int
     if pattern == "%f":
         pattern = "\d+.?\d*"
         convert = float
     if pattern == "%s":
         pattern = "\S+"

     while True:
         i = input(prompt).strip()
         if blank and not i:
             return None
         if lower:
             i = i.lower()
         flags = re.I if ignorecase else 0

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


# print( getinp("%d", "integer: ") )
# print( getinp("%f", "float: ") )
# print( getinp("%s", "string: ") )
# print( getinp("(y|n)", "y/n: ", lower=True) )

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

Blessed are the forgetful: for they get the better even of their blunders.
Friedrich Nietzsche



More information about the Tutor mailing list