What this error means

You tried to convert a string to a float using float(), but the string doesn't represent a valid decimal number. It might contain letters, special characters, or be empty.

Common causes

  • The string contains non-numeric characters (e.g., "abc", "hello123").
  • The string has spaces or other characters that aren't part of a number.
  • Empty string or string with only whitespace.
  • Multiple decimal points or invalid format.

Example that causes the error

price = "nineteen dollars"
num = float(price)  # ValueError: "nineteen dollars" can't be converted

value = "  "  # Just spaces
num = float(value)  # ValueError: empty/whitespace

How to fix it: clean the string first

Remove spaces and validate before converting:

price = " 19.99 "
num = float(price.strip())  # OK: removes spaces first

# Or check if it's valid:
price = "19.99"
try:
    num = float(price)
except ValueError:
    print("Not a valid number")

Handle user input safely

user_input = input("Enter a number: ").strip()
try:
    num = float(user_input)
    print(f"You entered: {num}")
except ValueError:
    print("That's not a valid number!")

Check if string is numeric

def is_float(value):
    try:
        float(value)
        return True
    except ValueError:
        return False

price = "19.99"
if is_float(price):
    num = float(price)
else:
    print("Invalid number format")