python学习笔记——错误、调试、测试

错误处理 练习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)

loggingdebuginfowarningerror等几个级别,当我们指定level=INFO时,logging.debug就不起作用了。同理,指定level=WARNING后,debuginfo就不起作用了。这样一来,你可以放心地输出不同级别的信息,也不用删除,最后统一控制输出哪个级别的信息。 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()

 

posted @ 2019-05-26 16:09  stacy_hu  阅读(234)  评论(0编辑  收藏  举报