函数返回先前的值

时间:2016-11-05 18:47:26

标签: python callback return

我希望将用户输入作为数字,检查其有效性并将其返回。如果号码无效,我希望重复输入过程。但是如果我输入:

  1. "5b"
  2. "50.4"
  3. 该功能不会返回50.4。而是返回5.0,因为第一个函数调用的 余数 被执行。如何修复上述问题,仅获取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)
    

    比较器变量是:

    comparator = ['0','1','2','3','4','5','6','7','8','9',',','.']
    

1 个答案:

答案 0 :(得分:2)

如果我理解你的问题,我认为你可以这样做:

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