0

I am working on a Paycheck calculator as a little side project for my portfolio and I have it so that users can input their own information (i.e. pay rate, hours worked, shift differentials, etc.) and parts of my code have inputs for variables:

payrate = float(input("What is your current payrate? $"))

When the code is run it asks the user to enter a value for their pay, but if they enter $20 instead of 20, I get:

ValueError: could not convert string to float: '$20'

How can I optimize my code so that it either ignores the $ when a user inputs something other than a float or it gives a rejection message to the user that I can write out myself in plain English so they know what to do?

Thank you!

Github link in case anyone wants to check it out for themselves (warning: still a massive WIP... so be gentle)

Muhubi
  • 1
  • 1

2 Answers2

0

Something like this should do what your question asks:

while True:
    s = input("What is your current payrate? $")
    try:
        payrate = float(s)
        break
    except ValueError:
        print("Couldn't parse you input as a number. Please try again")
        
print(f"Thanks, payrate is {payrate}")

The loop keeps going until a float is successfully parsed. Each time a parse fails (in other words, each time our attempt to convert the string s to a float raises an exception), it prints an informational message in the except block.

constantstranger
  • 9,176
  • 2
  • 5
  • 19
0

You an define a method called isfloat:

def isfloat(num):
    try:
        float(num)
        return True
    except ValueError:
        return False


payrate = input("What is your current payrate? $")
if isfloat(payrate):
    payrate = float(payrate)
    # Do some math
else:
    print("Please enter a number.")
    exit()
print(payrate)
NYC Coder
  • 7,424
  • 2
  • 11
  • 24