In my opinion, the if
statement is an interesting subject in Python. I would recommend to take into account the philosophy of the language when introducing it.
Most of time, I don't use if
as an alternative to the C++ switch
. I do prefer a dictionnary of functions.
I also try to follow the It's easier to ask forgiveness than permission
rule and I do prefer to catch exceptions.
I think that your examples should take that into account. So i wouldn't use the monster game
or the division by zero
ideas. It can be funny to implement but is not very pythonic in my opinion.
I mainly use if
as a filter.
I think you should'nt take any difficult algorithm as an example if your goal is to teach the syntax of the language. Learning how to program is certainly a sufficient challenge.
So I think any stupid example like the one below should work.
class Song:
def __init__(self, title, year):
self.title = title
self.year = year
songs = [Song('Blackbird', 1968), Song('Penny Lane', 1967), Song('Jenny Wren', 2005)]
for song in songs:
if song.year < 1970:
print song.title, 'by the Beatles'
else:
print song.title, 'is not a Beatles song'
It could also be a 1st step for the list comprehension if you plan to show it.
songs = [Song('Blackbird', 1968), Song('Penny Lane', 1967), Song('Jenny Wren', 2005)]
print [song.title for song in songs if song.year<1970]