Rahul Nair
Rahul Nair

Reputation: 39

Return value error

I am writing the code to calculate the balance of the salary.I have used a function called balance. But I am getting an error while returning the value.

print("WELCOME TO SALARY-BALANCE CALCULATOR")

def balance(salary,expense,bills):
    b=salary-expense-bills
    return b

print("Enter your salary :")
sal=input()

exp=input("Enter your personal expense ")
bil=input("Enter the bills amount")

bal=balance(sal,exp,bil)
print("The balance amount is : %d"%bal)

After running above code, I getting following error.

line 13, in <module>
  bal=balance(sal,exp,bil)
line 5, in balance
  b=salary-expense-bills
TypeError: unsupported operand type(s) for -: 'str' and 'str'

Can anyone tell where I am getting wrong?

Upvotes: 1

Views: 377

Answers (2)

rachid
rachid

Reputation: 2486

The problem is that input returns a string so you need to convert the string to float like the following (and maybe add some input validation throw an error if a string is entered instead of a number)

print("WELCOME TO SALARY-BALANCE CALCULATOR")

def balance(salary,expense,bills):
    b=salary-expense-bills
    return b

print("Enter your salary :")
sal= float(input())

exp= float(input("Enter your personal expense "))
bil= float(input("Enter the bills amount"))

bal=balance(sal,exp,bil)
print("The balance amount is : %f" % bal)

the best practice is to write a funciton that does the parsing like:

def parse_input_number( string ):
    try:
        return float(string)
    except Exception as error:
        print('the input is not a valid number')

Upvotes: 3

Shobhit
Shobhit

Reputation: 1116

Use this:

print("WELCOME TO SALARY-BALANCE CALCULATOR")

def balance(salary,expense,bills):
    b=salary-expense-bills
    return b

print("Enter your salary :")
sal=int(input())

exp=int(input("Enter your personal expense "))
bil=int(input("Enter the bills amount"))

bal=balance(sal,exp,bil)
print("The balance amount is : %d"%bal)

Upvotes: 1

Related Questions