Python Forum
writing user exceptions - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: writing user exceptions (/thread-13224.html)



writing user exceptions - ccm1776 - Oct-04-2018

hi guys. I would like to know how to reject invalid user inputs, or write exceptions in this loop. Ive never done it in a for loop, but I have to use one.

lowTaxStates=['California','Nevada', 'Arizona', 'Washington']
for i in range(6):
    employeeName= input('Enter name of employee: ')
    employeeSalary=float(input('Enter yearly salary of employee: '))
    employeeState= input('Enter full name of the state of residence for employee: ')
    if employeeSalary>100000.00:
        federalTaxes=0.20*employeeSalary
    else:
        federalTaxes=0.15*employeeSalary
    if employeeState in lowTaxStates:
        stateTaxes= 0.10*employeeSalary
    else:
        stateTaxes=0.12*employeeSalary
    netSalary=employeeSalary-federalTaxes-stateTaxes
    print('Net salary for employee is :', netSalary )
    print("""
    """)



RE: writing user exceptions - nilamo - Oct-04-2018

It looks like you're already doing some validation:
(Oct-04-2018, 07:05 PM)ccm1776 Wrote:
    if employeeState in lowTaxStates:
        stateTaxes= 0.10*employeeSalary
    else:
        stateTaxes=0.12*employeeSalary
The only thing you don't check first, is the salary. In that case, try a while loop to keep asking until a valid salary is given. Check this out:
>>> valid = False
>>> while not valid:
...   salary = input("Employee's salary: ")
...   try:
...     salary = float(salary)
...     valid = True
...   except ValueError:
...     print("That's not a valid value for salary.  Please try again.")
...
Employee's salary: fish
That's not a valid value for salary.  Please try again.
Employee's salary: $43,000.50
That's not a valid value for salary.  Please try again.
Employee's salary: 43000.50
>>> salary
43000.5