错误处理 练习1
from functools import reduce def str2num(s): try: return int(s) except Exception as e: return float(s) def calc(exp):
ss = exp.split('+') ns = map(str2num, ss) return reduce(lambda acc, x: acc + x, ns) def main(): r = calc('100 + 200 +345') print('100 + 200 +345 =', r) r = calc('99 + 88 + 7.6') print('99 + 100 +7.6=', r) main(
调试:
logging.info()
import logging logging.basicConfig(level=logging.INFO)
logging
有debug
,info
,warning
,error
等几个级别,当我们指定level=INFO
时,logging.debug
就不起作用了。同理,指定level=WARNING
后,debug
和info
就不起作用了。这样一来,你可以放心地输出不同级别的信息,也不用删除,最后统一控制输出哪个级别的信息。 logging
的另一个好处是通过简单的配置,一条语句可以同时输出到不同的地方,比如console和文件
单元测试
首先要使用unittest,编写一个测试类,从unittest.TestCase
继承
import unittest class Student(object): def __init__(self, name, score): self.name = name self.score = score def get_grade(self): if self.score >= 80: return 'A' if self.score >= 60: return 'B' if 0 <= self.score < 60: return 'C' else: raise ValueError("请输入正确的分数") class TestStudent(unittest.TestCase): def test_80_to_100(self): s1 = Student('Bart', 80) s2 = Student('Lisa', 100) self.assertEqual(s1.get_grade(), 'A') self.assertEqual(s2.get_grade(), 'A') def test_60_to_80(self): s1 = Student('Bart', 60) s2 = Student('Lisa', 79) self.assertEqual(s1.get_grade(), 'B') self.assertEqual(s2.get_grade(), 'B') def test_0_to_60(self): s1 = Student('Bart', 0) s2 = Student('Lisa', 59) self.assertEqual(s1.get_grade(), 'C') self.assertEqual(s2.get_grade(), 'C') def test_invalid(self): s1 = Student('Bart', -1) s2 = Student('Lisa', 101) with self.assertRaises(ValueError): s1.get_grade() with self.assertRaises(ValueError): s2.get_grade() if __name__ == '__main__': unittest.main()