summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--LectureNotesOnPython.rst22
1 files changed, 22 insertions, 0 deletions
diff --git a/LectureNotesOnPython.rst b/LectureNotesOnPython.rst
index 5bc2d63..6b59791 100644
--- a/LectureNotesOnPython.rst
+++ b/LectureNotesOnPython.rst
@@ -578,6 +578,28 @@ def,函数名,参数列表:
+初学者面对函数时, 往往会卡住。 在开始函数体时, 往往会忘记缩进。
+
+比如将一段代码移植到函数时, 往往会手足无措。 原因, 经验不够。
+
+**练习** 下面的代码可以统计字符串中各个词出现的次数。 将这个代码片段转换成函数 freq(s), 函数返回一个列表, 列表中每个元素是元组, (word, frequency), word代表词, frequency代表该词出现的次数。
+
+
+.. code:: python
+
+
+ fruit = 'Apple BANANA apple'
+ fruit = fruit.lower()
+ flst = fruit.split()
+ for f in set(flst):
+ n = flst.count(f)
+ print('%s has appeared %d times' % (f, n))
+
+
+**练习** 重写上面的freq函数, 使得返回的列表是按照frequency从大到小排好序的, 如 [('apple', 2), ('banana', 1)]。 apple在banana之前, 因为apple出现的次数更多。
+
+
+
Python的关键词
--------------------------------