在Python中使用条件句Try和Except

2024-04-25 23:33:59 发布

您现在位置: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语句,直接跳转到else语句……但由于某种原因,这并没有发生。另外,当我制作同一程序的第一个版本时,没有try和except位:

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

这个很好用。你知道吗


Tags: inputyourbaserawifrateisadditional
2条回答

字符串整数的转换不会保存到小时。为此,请执行以下操作:

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

int(hours)不到位。从docs

Return an integer object constructed from a number or string x, or return 0 if no arguments are given

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

hours = int(hours)

相关问题 更多 >