返回值错误

时间:2017-11-12 13:14:58

标签: python

我正在编写代码来计算薪水的余额。我使用了一个名为balance的函数。但是在返回值时我收到错误。

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)

运行上面的代码后,我收到了以下错误。

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'

谁能告诉我哪里出错?

2 个答案:

答案 0 :(得分:3)

问题是输入返回一个字符串,所以你需要将字符串转换为float,如下所示(如果输入字符串而不是数字,可能会添加一些输入验证会抛出错误)

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)

最佳做法是编写一个执行解析的函数:

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

答案 1 :(得分:1)

使用此:

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)