Last active
August 18, 2018 13:41
-
-
Save nikodemusk/ed1aab0f878dd701d5f8d7df8e64c5d9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Validating input in Python 3 | |
validSymbolsInInt = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-"] | |
validSymbolsInFloat = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "."] | |
def readInt(number): | |
charCounter = 0 | |
for num in number: | |
charCounter += 1 | |
if not num in validSymbolsInInt: | |
return False | |
if (num == "-" and charCounter > 1) or (num == "-" and len(number) == 1): | |
return False | |
return number | |
def readFloat(number): | |
numberOfDecPoints = 0 | |
charCounter = 0 | |
digits = validSymbolsInFloat[:10] # The valid digits | |
numberString = ''.join(digits) | |
# Are there any valid digits at all in input? | |
matchFlag = 0 | |
for num in number: | |
if numberString.find(num) != -1: | |
matchFlag = 1 | |
if not matchFlag: | |
return False | |
# Other invalid chars in input? | |
for num in number: | |
charCounter += 1 | |
if not num in validSymbolsInFloat: | |
return False | |
elif num == ".": | |
numberOfDecPoints += 1 | |
# Combinations and placements of valid chars may | |
# make the input invalid. | |
if (num == "-" and charCounter > 1) or ((num == "-" or num == ".") and len(number) == 1) or numberOfDecPoints > 1: | |
return False | |
# Return the valid number | |
return number | |
numberInt = input("Enter an integer -> ") | |
while not readInt(numberInt): | |
print("No integer, please try again.") | |
numberInt = input("Enter an integer -> ") | |
numberInt = int(numberInt) | |
print("Success, you entered", numberInt) | |
print() | |
numberFloat = input("Enter a floating point number -> ") | |
while not readFloat(numberFloat): | |
print("No number, please try again.") | |
numberFloat = input("Enter a floating point number -> ") | |
numberFloat = float(numberFloat) | |
print("Success, you entered", numberFloat) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment