尝试使用Python中的条件除外

时间:2015-07-19 05:07:36

标签: python

我是初学者,并在Python练习中编写了以下程序:

try:
    hours = raw_input ('Enter number of hours \n')
    int(hours)
    rate = raw_input ('Enter your hourly rate \n')
    int(rate)
except:
    print 'Enter an integer value'
    quit()
if hours > 40:
    overtime = hours - 40
    base = 40*rate
    additional = overtime * (1.5 * rate) 
    print 'Your total wage including overtime is', additional + base
else:
    wage = rate * hours
    print 'Your total wage before tax is', wage

但是,我收到了TypeError in line 10 that reads unsupported operand type(s) for -: 'str' and 'int'

奇怪的是,当我输入小时数为10并且评为5时,它应该跳过第一个if语句并直接跳到其他地方......但由于某些原因不会发生。此外,当我在没有尝试和除了位的情况下制作相同程序的第一个版本时:

hours = float(raw_input('Enter number of hours \n'))
rate = float(raw_input('Enter your hourly rate \n'))
if hours > 40:
    overtime = hours - 40
    base = 40*rate
    additional = overtime * (1.5 * rate) 
    print 'Your total wage including overtime is', additional + base
else:
    wage = rate * hours
    print 'Your total wage before tax is', wage

这很好用。

2 个答案:

答案 0 :(得分:1)

int(hours)不在原位。来自docs

  

返回 从数字或字符串x构造的整数对象,如果没有给出参数,则返回0

您需要将其重新分配回变量

hours = int(hours)

答案 1 :(得分:0)

您从字符串 int 的转换不会保存到小时。要做到这一点,请执行以下操作:

hours=int(hours) # this is in the 3rd line of your code. Do the same for rate
相关问题