What & How & Why

差别

这里会显示出您选择的修订版和当前版本之间的差别。

到此差别页面的链接

两侧同时换到之前的修订记录前一修订版
后一修订版
前一修订版
cs:fundamental:cs61a:week_1 [2023/09/26 04:26] – [Compound Statements] codingharecs:fundamental:cs61a:week_1 [2023/10/27 05:54] (当前版本) – [Conditional statement] codinghare
行 281: 行 281:
 这是一种递归的结构。 这是一种递归的结构。
 ===Local Assignment=== ===Local Assignment===
 +用户自定义的函数是在对应的 local frame 中运行的。local frame 在该函数被调用时创建;函数体中的 ''return'' statement 会起到重定向的作用。函数什么时候结束取决于
 +  * 第一个 ''return'' statement 什么时候被执行
 +  * 返回的值
 +赋值语句可以处于函数内部。任何函数内部的赋值,其绑定信息都存储于local frame,对外部的 name 不造成任何影响。
 +===Conditional statement===
 +<code py>
 +if <expression>:
 +    <suite>
 +elif <expression>:
 +    <suite>
 +else:
 +    <suite>
 +</code>
 +  * 首先会评估 header
 +  * 某个 header 为 true, 则执行该 Header 下的 suite,其他的 suite 将会被跳过。
 +===Iteration===
 +<code py>
 +while <expression>:
 +    <suite>
 +</code>
 +===Testing===
 +==Assertions==
 +python 中可以使用 ''assert'' statement 做验证。如果 ''assert'' 返回的对象为 ''True'',那么什么也不会发生。否则,错误会被抛出:
 +<code py>
 +>>> def fib_test():
 +        assert fib(2) == 1, 'The 2nd Fibonacci number should be 1'
 +        assert fib(3) == 1, 'The 3rd Fibonacci number should be 1'
 +        assert fib(50) == 7778742049, 'Error at the 50th Fibonacci number'
 +</code>
 +==Doctest==
 +//docstring// 中可以包含 test case,用于测试:
 +<code py>
 +>>> def sum_naturals(n):
 +        """Return the sum of the first n natural numbers.
 +
 +        >>> sum_naturals(10)
 +        55
 +        >>> sum_naturals(100)
 +        5050
 +        """
 +        total, k = 0, 1
 +        while k <= n:
 +            total, k = total + k, k + 1
 +        return total
 +        
 +>>> from doctest import testmod
 +>>> testmod()
 +TestResults(failed=0, attempted=2)
 +</code>