Skip to content

Instantly share code, notes, and snippets.

@Starfox64
Created November 16, 2015 10:08
Show Gist options
  • Save Starfox64/e50efcc429c27f7b3a5d to your computer and use it in GitHub Desktop.
Save Starfox64/e50efcc429c27f7b3a5d to your computer and use it in GitHub Desktop.
Python function to request a user input while handling the input errors without having a messy code.
def parseInput(message, returnType="int", callback=None):
while True:
res = input(message)
if returnType == "int":
try:
returnVal = int(res)
except ValueError:
continue
if not callback or callback(returnVal):
return returnVal
elif returnType == "float":
try:
returnVal = float(res)
except ValueError:
continue
if not callback or callback(returnVal):
return returnVal
elif returnType == "str":
if not callback or callback(res):
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment