Will Murton Will Murton - 3 months ago 5x
Python Question

How do i trap incorrect inputs of various types for a float?

I am a school student with an assessment tomorrow, and My practice Code is the following:

'''A local technology company has various options for buying cell phones on credit:
• Pay off monthly over six month with no interest
• Pay off monthly over 12 months with 5% interest on the money owing after 6 months and up to 12 months

They have asked you to design and create a program that they can use to work out the various values depending on the customer’s requirements and initial sales price. The initial sales price includes GST. As output, they want the name of the person displayed, sales price, interest to be paid, the term of repayment and the amount they will be paying each month.

The program needs to run continuously until a rogue value Q is entered. You are expected to design and implement a user-friendly approach. Also make sure the program is robust enough to survive any random values entered. Use test data that will cover all possible combinations.
Created By: William
Date: 26th June 2016'''

#Get users name and trap false inputs
name = input("What is your name? ")
while name.isnumeric() or name == "":
print("That isn't a valid option. Please enter an alphabetical name.")
name = input("What is your name? ")

#get sales price and trap false inputs
sales_price = float(input("How much does your phone cost? $"))
while sales_price.isnumeric() or sales_price == "":
print("That isn't a number! Please enter a value above $0")
sales_price = float(input("How much does your phone cost? $"))

print(name, sales_price)

My question, as said in the description, how can i trap inputs such as a letter or a negative value in the sales price?
Any help is gratefully appreciated.


You should take advantage of the fact that float() raises ValueError when it is given a string that can't be converted to a float.

In the below code, the while loop will be repeated as long as the user inputs either a negative number or a string that can't be converted to a float.

valid_input = False
while not valid_input:
        sales_price = float(input("How much does your phone cost? $"))
        if sales_price < 0:
            raise ValueError
    except ValueError:
        valid_input = True