Check if the user is typing in numeric numbers. Don't want letters
I would like to know the easiest way to check it the user typing in a letter versus a number. If the user types in a letter it would give them an error message and give them the question back. Right now I have it so when the user enters a 'q' it will exit the script.
if station == "q":
开发者_开发知识库 break
else:
#cursor.execute(u'''INSERT INTO `scan` VALUES(prefix, code_id, answer, %s, timestamp, comport)''',station)
print 'Thank you for checking into station: ', station
I need it to loop back to the question asking for the station.
Just using python built-in method
str.isdigit()
SEE http://docs.python.org/library/stdtypes.html
e.g.
if station.isdigit():
print 'Thank you for checking into station: ', station
else:
# show your error information here
pass
Try this (using YeJiabin's answer)
def answer():
station = raw_input("Enter station number: ")
if not(str.isdigit(station)):
answer()
Haven't tested that!
With the requirements that you're looking to see if the input string contains anything other than the digits 1..9:
>>> import re
>>> # create a pattern that will match any non-digit or a zero
>>> pat = re.compile(r"[\D0]")
>>> pat.search("12345")
>>> pat.search("123450")
<_sre.SRE_Match object at 0x631fa8>
>>> pat.search("12345A")
<_sre.SRE_Match object at 0x6313d8>
>>> def CheckError(s):
... if pat.search(s):
... print "ERROR -- contains at least one bad character."
...
>>> CheckError("12345")
>>> CheckError("12a")
ERROR -- contains at least one bad character.
>>> CheckError("120")
ERROR -- contains at least one bad character.
>>>
精彩评论