Home > Blockchain >  unsupported operand type(s) for *: 'NoneType' and 'NoneType'
unsupported operand type(s) for *: 'NoneType' and 'NoneType'

Time:04-11

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

main()

tried to convert "dollars" and "percent" but it didn't work, I searched but most of the things didn't work and i didn't understand some because I'm new to python

CodePudding user response:

You aren't returning anything from your functions. If you want a value returned, then you must do so. Use return p instead of print(p). Utility functions should not PRINT their results. They should RETURN their results and let the caller decide what to do with it.

def dollars_to_float(d):
    d = d.replace('$', '')
    d = float(d)
    return d
def percent_to_float(p):
    p = p.replace('%', '')
    p = float(p)
    p = p/100
    return p

CodePudding user response:

functions are something that return a value: it can be anything like int or string... if you dont return anything at end of your caculation in function, it return None that means null or nothing and you cant use None in arithmatic statement, so return d or p, instead of print and use it in your main function:

def dollars_to_float(d):
    d = d.replace('$', '')
    d = float(d)
    return d

def percent_to_float(p):
    p = p.replace('%', '')
    p = float(p)
    p = p/100
    return p

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

main()

any function send it's last value to others by return and others can use it for print or other calculation

  • Related