为什么我在这里得到str和int的类型顺序?

时间:2017-09-24 20:43:13

标签: python python-3.x

我的任务是:

  

编写程序以获取员工姓名和薪水。计算   联邦税和州税基于以下标准:如果   工资大于100000然后计算20%的联邦税   否则计算15%的联邦税计算州税   5%计算员工的净工资。计算净额   工资,从工资总额中扣除联邦和州税。

我的代码:

employeename = input("Enter the employee's name:")
grosssalary = input("Enter the employee's gross salary: $")
if grosssalary > 100000:
    federaltax = 0.20
else:
    federaltax = 0.15
statetax = 0.05
netsalary = float(grosssalary) - float(grosssalary * federaltax) - float(grosssalary * statetax)
print (employeename,"'s net salary is $",netsalary)

输出:

Enter the employee's name:Ali
Enter the employee's gross salary: $1000
Traceback (most recent call last):
  File "/home/ubuntu/workspace/Untitled4", line 3, in <module>
    if grosssalary > 100000:
TypeError: unorderable types: str() > int()
Process exited with code: 1

3 个答案:

答案 0 :(得分:1)

input()在Python 3.x中返回类型str

所以你正在做grosssalary > 100000 str > int

要解决,请使用:

gross_salary = int(input("Enter the employee's gross salary: $"))

答案 1 :(得分:1)

在Python 3.x中,input()的返回值始终为str类型,因此您要将str对象与int对象进行比较,从而产生类型错误。您不能这样做,您必须在比较之前将其转换为intfloat

试试这个:

grosssalary = float(input("Enter the employee's gross salary: $"))

答案 2 :(得分:0)

错误很明显,您尝试检查字符串是否大于int且不可接受。

您应首先将字符串转换为int然后进行检查,您的代码应如下所示:

employeename = input("Enter the employee's name:")
grosssalary = input("Enter the employee's gross salary: $")
if int(grosssalary) > 100000:
    federaltax = 0.20
else:
    federaltax = 0.15
statetax = 0.05
netsalary = float(grosssalary) - float(grosssalary * federaltax) - float(grosssalary * statetax)
print (employeename,"'s net salary is $",netsalary)

你还应该先检查字符串是否为int,为此,你的检查应如下:

if grosssalary.isdigit()

    if int(grosssalary) > 100000:

        federaltax = 0.20
    else:
        federaltax = 0.15
else:
    print("bad entry")