如何包含try:和except:用于异常处理?

时间:2016-05-25 15:43:47

标签: python python-2.7 exception exception-handling try-catch

我尝试在此程序中包含try:except:以捕获文本字符串异常,但无法弄清楚如何实现。如何将try:except:包含在异常处理中?

#!/usr/bin/python2.7

h = float(raw_input('Enter Hours: '))
r = float(raw_input('Enter Rate: '))
if h > 40 :
    p = h * r + (h - 40) * r * 0.5
else :
    p = h * r
print 'Pay:', p

2 个答案:

答案 0 :(得分:1)

#!/usr/bin/python2.7

def calc_pay(h, r) :
    if h <= 0 or r <= 0 :
        return None
    elif h > 40 :
        return (h * r + (h - 40) * r * 0.5)
    else :
        return (h * r)

try :
    h = float(raw_input('Enter Hours: '))
    r = float(raw_input('Enter Rate: '))
    p = calc_pay(h, r)
    print 'Pay:', p
except :
    print "Enter Numeric Data"

答案 1 :(得分:0)

你只需要使用try除了

def num(s):
    try:
        return float(s)
    except :
        return None
h = num(raw_input('Enter Hours: '))

现在您需要要求有效的回复。例如。

h = None
p = None
while (h is None):
    h = num(raw_input('Enter Hours: '))
while (p is None):
    p = num(raw_input('Enter Price: '))

这取决于您希望如何处理剩余的处理。有些人可能更愿意返回0,如果它是无效的条目,因为0价格或0小时也将无效,因此测试&gt; 0

def num(s):
    try:
        return float(s)
    except :
        return 0.0
h = num(raw_input('Enter Hours: '))

h = 0.0
p = 0.0
while (h <= 0.0):
    h = num(raw_input('Enter Hours: '))
while (p <= 0.0):
    p = num(raw_input('Enter Price: '))