-1

Upon entering an input, say $50.00, I get an error that says ValueError: could not convert string to float: '$50.00'. I already have dollars.removeprefix("$") in line 10, the .removeprefix() method simply does nothing. What am I doing wrong? Full code below:

def main():
    dollars = dollars_to_float(input("How much was the meal? "))
    percent = percent_to_float(input("What percentage would you like to tip? "))
    percent = percent / 100
    tip = dollars * percent
    print(f"Leave ${tip:.2f}")


def dollars_to_float(dollars):
    dollars.removeprefix("$")
    return float(dollars)


def percent_to_float(percent):
    percent.removesuffix("%")
    return float(percent)


main()
  • 2
    Save the result to a variable. – Mateen Ulhaq Jun 04 '22 at 21:26
  • 1
    Your script works fine adding only numbers and ignoring the currencty, but I'd go with this - force a numeric input. https://stackoverflow.com/questions/5424716/how-to-check-if-string-input-is-a-number – JonTout Jun 04 '22 at 21:30

1 Answers1

0

You are not reassigning your result to a variable.

def main():
    dollars = dollars_to_float(input("How much was the meal? "))
    percent = percent_to_float(input("What percentage would you like to tip? "))
    percent = percent / 100
    tip = dollars * percent
    print(f"Leave ${tip:.2f}")


def dollars_to_float(dollars):
    dollars = dollars.removeprefix("$")
    return float(dollars)


def percent_to_float(percent):
    percent = percent.removesuffix("%")
    return float(percent)

You should really improve your code to perform some more input validation. What happens to your script if I do this?

>>> How much was the meal? 
>>> 50$

A simple idea to make it more robust:

import re

def dollars_to_float(dollars):
    # Extract numbers, ignore all else
    dollars = re.sub(r"[^1-9\.]", "", dollars)
    return float(dollars)
965311532
  • 506
  • 3
  • 14