Sign InCoursewareNuggetsTutorials AboutClassesCodePad

Story Within a Story

It was a dark and stormy night. The crew said to the captain, 
"Captain, tell us a story!" The captain said to the crew:
"It was a dark and stormy night. The crew said to the captain,
"Captain, tell us a story!" The captain said to the crew:
"It was a dark and stormy night." ...

This story has a story teller that tells the same story and it goes on forever. The following code prints the story by defining a function called story. After printing out the beginning of the story, it calls itself to print the same story that the story teller says. However, this code never ends.

Recursion Story
# A story that never ends def story(): print "It was a dark and stormy night. The crew said to the captain, " print "\"Captain, tell us a story!\" The captain said to the crew: " story() story()

In practice, we need to specify a point to stop. Otherwise, our program will run forever and eventually run out of memory. One way is to set up a counter to control it. The following code will end when the story has been told for 5 times. We use a parameter count to remember how many times a story still needs to be told. Each time story( ) calls itself, count decreases by 1. When count reaches 0, story( ) ends without calling itself again.

# A story that tells the same story def story(count): if count == 0: print "The end." return print "It was a dark and stormy night. The crew said to the captain, " print "\"Captain, tell us a story!\" The captain said to the crew: " story(count - 1) story(5)
© CS Wonders·About·Classes·Cheatsheet