zoukankan      html  css  js  c++  java
  • 解读python小练习

    1.新建一个函数,判断是不是int 类型,并测试,不是抛出错误
    def adder(x, y):
    """
    Return x + y if they are both integers
    """
    if not (isinstance(x, int) and isinstance(y, int)):
    raise TypeError("Inputs must be integers")
    return x + y
    res = adder(4,5)
    print(res)
    2.
    import unittest
    from adder import adder

    class Test(unittest.TestCase):

    def test_adder_errors(self):
    "Tests ensuring errors in data that cause TypeError raises."
    self.assertRaises(TypeError, adder, "123", "456")
    self.assertRaises(TypeError, adder, "123", 456)
    self.assertRaises(TypeError, adder, "123", 456)
    self.assertRaises(TypeError, adder, 1.23, 456)

    def test_adder_successes(self):
    "Tests ensuring that valid data passes."
    self.assertTrue(adder(1, 2) == 3, "1 + 2 is not 3")

    if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.test_adder_errors', 'Test.test_adder_succusses']
    unittest.main()
    tip:
    #理解if __name__ == "__main__"
    def main():
    print("we are in %s" % __name__ )
    print(1)
    if __name__ == "__main__": #这个功能还有一个用处:调试代码的时候,在”if __name__ == '__main__'“中加入一些我们的调试代码,我们可以让外部模块调用的时候不执行我们的调试代码,但是如果我们想排查问题的时候,直接执行该模块文件,调试代码能够正常运行!
    main()
    print(2)
    3.
    import sys
    for n,arg in enumerate(sys.argv): #对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值
    print(n,":", arg)
    # list = ["这","是","一个","测试"]
    # for i in range(len(list)):
    # print(i,list[i])
    # list1 = ["这","是","一个","测试"]
    # for index,item in enumerate(list1):
    # print(index,item)

    4.
    def zip_errors(z):
    """
    Validate z as either NNNN or NNNN-NNNN.
    """
    l = len(z)
    if l not in(5,10):
    return "Zip codes should be 5 or 10 characters long"
    if (not z[:5].isdigit() or
    l == 10 and not z[6:].isdigit()):
    return "Zip code contains non-numeric characters"
    if l == 10 and z[5] != "-":
    return "Ten-digit zips must have a dash between the two parts"
    return
    tip:
    import unittest
    def cal(a,b):
    return a + b
    class CalTest(unittest.TestCase):
    def testA(self):
    expected = 6
    result = cal(2,4)
    self.assertEqual(expected,result);
    def testB(self):
    expected = 0
    result = cal(2,1)
    self.assertEqual(expected,result)
    if __name__ == '__main__':
    unittest.main() #执行 unittest.main() ,该函数会负责运行测试,它会实例化所有TestCase的子类,并运行其中所有以test打头的方法。
    #多个测试类
    #coding=utf-8
    import unittest
    from test1 import CalTest1
    from test2 import CalTest2
    if __name__=='__main__':unittest.main()

  • 相关阅读:
    Java学习----不变的常量
    Java学习----Java数据类型
    Java学习----Java程序结构
    Java学习----main详解
    (转)你知道Android也有安全模式吗?(地球人都知道了吧)
    Android学习----打印日志Log
    Android学习----五大布局
    Android学习-----Button点击事件几种写法
    mysql建立索引 删除索引
    MySQL查看SQL语句执行效率
  • 原文地址:https://www.cnblogs.com/Jt00/p/7444256.html
Copyright © 2011-2022 走看看