Discuss / Python / 打卡第十天

打卡第十天

Topic source

皆由唧唧

#1 Created at ... [Delete] [Delete and Lock User]

请问:

assert b'abcd' == safe_base64_decode(b'YWJjZA=='), safe_base64_decode('YWJjZA==')

这个 assert 语句该怎么理解,我看到很多兄弟的作业这么写的:

def safe_base64_decode(s):
    if len(s) % 4 != 0:
        s = s + b'=' * (4-len(s)%4)
    return base64.b64decode(s)

定义这个函数时,参数 s 默认就是 bytes类型了,但上面的assert语句中,

safe_base64_decode('YWJjZA==')

这里 传入的是一个字符串,按理说要报错才对,怎么结果显示的是 ok?

皆由唧唧

#2 Created at ... [Delete] [Delete and Lock User]
def safe_base64_decode(s):
     if isinstance(s,bytes):
         s=str(s)
     if "b'" in s:
        s=s[2:-1]
     a = 4 - len(s)%4
     s = s + '='*a
     return base64.b64decode(s)

皆由唧唧

#3 Created at ... [Delete] [Delete and Lock User]
def safe_base64_decode(s):
     if isinstance(s,bytes):
         s=str(s)[2:-1]
     a = 4 - len(s)%4
     s = s + '='*a
     return base64.b64decode(s)

皆由唧唧

#4 Created at ... [Delete] [Delete and Lock User]

这样是不是说明测试代码中的 assert 语句有一点点问题,assert 语句不能判断多个表达式?

>>> assert 0 == 1-1, 2-2
>>> assert 0 == 1-1, 3-2
>>> assert 0 == 1-1, 10/0
>>> assert 0 == 2-1, 2-2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: 0
>>> assert 0 == 2-1, 10/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
assert <condition>,<error message>

如果<condition>为真,继续执行后面语句(跳过error message),否则,输出(执行)<error message>


  • 1

Reply