Search code examples
pythonfunctionpython-3.7valueerror

Passing 'ValueError' & 'continue' in a function and call it


I am trying to check user inputs to ensure that: 1) It is a floating number 2) Floating number is not negative

I am trying to put above 2 checks into a function and call it after user has input into a variable.

However, I cant seem to put 'ValueError' & 'continue' in a function that I can call. Is this possible?

I have tried below code, but it repeats from the top when I key in 't' for salCredit, or any of the next few variables. The code will work if I were to repeat 'ValueError' & 'continue' for every variable. I'm just wondering if there is a shorter way of doing do?

def interestCalculator():

    #User inputs required for calculation of interest earned.
    while True:
        try: 
            mul_AccBal = float(input("Enter your Account Balance: "))
            #checkInputError(accBal)

            salCredit = float(input("Enter your Salary: "))
            #checkInputError(salCredit)

            creditCard = float(input("Credit Card Spend (S$): "))
            #checkInputError(creditCard)

        except ValueError:
            print("Please enter a valid number.")
            continue

def checkInputError(userInput):
    if userInput < 0:
        print("Please enter a positive number.")

interestCalculator()

Expected results:

Scenario 1: if user inputs 't'

Enter your Account Balance: 5000
Enter your Salary: t 
Please enter a valid number.
Enter your Salary: 500

Scenario 2: if user inputs negative number

Enter your Account Balance: 5000
Enter your Salary: -50 
Please enter a valid number.
Enter your Salary: 500

Current results:

Scenario 1: if user inputs 't'

Enter your Account Balance: 5000
Enter your Salary: t 
Please enter a valid number.
Enter your Account Balance: 

Scenario 2: if user inputs negative number

Enter your Account Balance: 5000
Enter your Salary: -50 
Please enter a positive number.
Credit Card Spend (S$):

Solution

  • You could create a function that continues prompting for input until a valid float is input

    def get_float_input(prompt):
        while True:
            try:
                user_input = float(input(prompt))
                if user_input < 0:
                    print("Please enter a positive number.")
                    continue  # start the while loop again
                return user_input  # return will break out of the while loop
            except ValueError:
                print("Please enter a valid number.")
    
    mul_AccBal = get_float_input("Enter your Account Balance: ")
    salCredit = get_float_input("Enter your Salary: ")
    creditCard = get_float_input("Credit Card Spend (S$): ")