web analytics
Skip to main content
elephant_jokes

Learning recursion through elephant jokes

(Note: This post could also be titled “Telling elephant jokes with python”)

When teaching my students how to understand recursion, I always refer to the classic elephant joke: “how do you kill a blue elephant? With a blue elephant gun”.

They look amazed at first, until they notice that the joke is indeed a recursion, since, in order to kill an elephant with a certain colour, you should make it change the colour, then try to kill it again, until it turns blue, and the recursion ends.

So, I just implemented a little python program, with an “Elephant” class and a “kill” recursive method, in order to better demonstrate how recursion works. Have fun:

class Elephant():
	def __init__(self, colour):
		self.colour = colour
		
	def change_colour(self, new_colour):
		self.colour = new_colour
		print "Elephant's colour turns to " + self.colour
		
	def hold_nose(self):
		print "Hold elephant's nose..."
		self.change_colour('blue')
		
	def tickle(self):
		print "Tickle the elephant..."
		self.change_colour("pink")

	def strangle(self):
		print "Strangle the elephant..."
		self.change_colour("red")
	
	def kill(self):
		if self.colour == 'blue':
			print "Kill the elephant with a blue elephant gun!"
		elif self.colour == 'pink':
			self.hold_nose()
			self.kill()
		elif self.colour == 'red':
			self.tickle()
			self.kill()
		elif self.colour == 'white':
			self.strangle()
			self.kill()
		else:
			print "There aren't " + self.colour + " elephants!"

e = Elephant('blue')
print "How to kill a " + e.colour + " elephant?"			
e.kill()
print ""

e = Elephant('pink')
print "How to kill a " + e.colour + " elephant?"			
e.kill()
print ""

e = Elephant('red')
print "How to kill a " + e.colour + " elephant?"			
e.kill()
print ""

e = Elephant('white')
print "How to kill a " + e.colour + " elephant?"			
e.kill()
print ""

e = Elephant('yellow')
print "How to kill a " + e.colour + " elephant?"			
e.kill()
print ""

Here you have the program results:

How to kill a blue elephant?
Kill the elephant with a blue elephant gun!

How to kill a pink elephant?
Hold elephant’s nose…
Elephant’s colour turns to blue
Kill the elephant with a blue elephant gun!

How to kill a red elephant?
Tickle the elephant…
Elephant’s colour turns to pink
Hold elephant’s nose…
Elephant’s colour turns to blue
Kill the elephant with a blue elephant gun!

How to kill a white elephant?
Strangle the elephant…
Elephant’s colour turns to red
Tickle the elephant…
Elephant’s colour turns to pink
Hold elephant’s nose…
Elephant’s colour turns to blue
Kill the elephant with a blue elephant gun!

How to kill a yellow elephant?
There aren’t yellow elephants!