Reputation: 971
I want to get the users input as a number, check its validity and return it. If the number is invalid, I wish to repeat the input process. However if I type:
"5b"
"50.4"
The function doesn't return 50.4
. Instead it returns 5.0
, as the remainder of the first function call is executed. How can I fix the above issue, to only get 50.4
?
def inputGoal ():
goalFiltered = ""
print ('1: ' + str(goalFiltered))
goal = input("Input number: ")
for char in goal:
matched = False
for sign in comparator:
if (sign == char):
matched = True
if (char != ','):
goalFiltered += sign
elif (char == ','):
goalFiltered += '.'
if (matched == False):
print ("Please repeat input, valid characters are: 0 1 2 3 4 5 6 7 8 9 , .")
inputGoal()
#return
goalFiltered = float(goalFiltered)
return (goalFiltered)
The comparator variable is:
comparator = ['0','1','2','3','4','5','6','7','8','9',',','.']
Upvotes: 0
Views: 811
Reputation:
If I understood your problem correctly, I think you can just do this:
while True:
ask = input("Input the number:\t") #The \t just puts a tab so it looks nice
if ask == float(ask):
break
else:
print("The number is incorrect. Try again.")
continue
Upvotes: 2