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()
>Solution :
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)