[Edu-sig] simple guessing games

kirby urner kirby.urner at gmail.com
Mon Sep 11 07:32:45 CEST 2006

Given we've learned how dot notation triggers behaviors, of strings,
of lists, of modules, we now look at our snake's internal __rib__

Mnemonic (also legal Python, even if __rib__ isn't really a special name [1]):

class Snake:
	"""triggering reflexes..."""
	def __rib__(self):  pass
	def __rib__(self):  pass
	def __rib__(self):  pass
	def __rib__(self):  pass
	def __rib__(self):  pass
	def __rib__(self):  pass
	def __rib__(self):  pass
	def __rib__(self):  pass

Both __init__ and __repr__ are special methods, ready for our use.[2]

[1]  http://www.dbforums.com/showthread.php?t=407220
[2]  http://www.python.org/doc/current/ref/specialnames.html


import random

class Secret:

	def __init__(self):
		self.__hidden = random.randint(0,100)

	def guess(self, val):
		if val > self.__hidden:
			print "too high"
		elif val < self.__hidden:
			print "too low"
			print "You guessed it!"

	def __repr__(self):
		return 'A secret number'


>>> from sillygame import Secret
>>> thesecret = Secret()

>>> thesecret.guess(10)
too low

>>> thesecret.guess(50)
too low

>>> thesecret.guess(75)
too low

>>> thesecret.guess(85)
too low

>>> thesecret.guess(95)
too low

>>> thesecret.guess(100)
too high

>>> thesecret.guess(96)
You guessed it!


Good work mom!


More information about the Edu-sig mailing list