今天在无意之中,想到了一个有关给新人解释递归的超级简单例子。
内容是有关一个经典故事
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| def TellStory():
print("从前有座山")
print("山上有座庙")
print("庙里有个老和尚和一个小和尚")
print("老和尚在给小和尚讲故事")
print("故事的内容是:\n")
TellStory()
TellStory()
|
输出结果是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| 从前有座山 山上有座庙 庙里有个老和尚和一个小和尚 老和尚在给小和尚讲故事 故事的内容是:
从前有座山 山上有座庙 庙里有个老和尚和一个小和尚 老和尚在给小和尚讲故事 故事的内容是:
从前有座山 山上有座庙 庙里有个老和尚和一个小和尚 老和尚在给小和尚讲故事 故事的内容是:
从前有座山 山上有座庙 庙里有个老和尚和一个小和尚 老和尚在给小和尚讲故事 故事的内容是:
...
|
这个例子相当于老和尚讲的内容由TellStory()来进行阐述
当然,英语例子如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| def TellStory():
print("Once upon a time, there was a mountain")
print("On the mountain, there was a temple")
print("In the temple, there was an old monk and a young monk")
print("The old monk was telling a story to the young monk")
print("The story is:\n")
TellStory()
TellStory()
|