views:

217

answers:

10

What would be a good set of programming exercises that would help Python newbies to learn the use of the "if ... else" construct? I could cook up the following, do you know of any more?

  1. Find the largest/smallest of three numbers.
  2. Given a date (year, month, day), find the next date.

Most of the intended audience have not had much of an exposure to programming before, and I am keen on getting them used to thinking correctly about "if ... else" (and all the rest of it, in due course).

Thanks, Philip

A: 

I did demonstration of the subject in DaniWeb by number guess game. Something similar maybe?

Using if..else in print statement instead of multiline if is my favorite use of the construct.

I saw other answers to suggest things for normal if statement so I cooked up one myself:

I think of practical value would be to use if in break statement as reaction to user input. Same time you can teach try...except ie when not to use if in Python.

Tony Veijalainen
+1  A: 

Try a simple game, like if you press 'L', turn left, if you press 'R', turn right, if there's a monster, you die etc.

Skilldrick
Skilldrick, don't we need loops for that? We haven't reached the loop stage yet.Thanks.
gphilip
I'm thinking really basic, with lots of repetition. So, rather than use a loop, just repeat the code. Has the added benefit that you could go back later and show how few lines of code you'd need if you did it with a loop :)
Skilldrick
Thanks Skilldrick, will think this one over and see what I can make out of it.
gphilip
+2  A: 

"Figure out whether a given year is a leap year" springs to mind almost immediately. Just give 'em the rules and turn 'em loose.

Other possibilities (albeit with stuff other than if statements):

  • Hunt the Wumpus (you may have to google for this one, I'm showing my age).
  • The perennial "detect a win in a Tic Tac Toe (Noughts and Crosses) game" (you could do this with eight if statements if you don't want a loop).
  • Guessing a number between 1 and 100 as quickly as possible (higher, lower).

For nothing but if/else statements, the leap year one is good. You could also consider:

  • Test if a number is a multiple of 3, 5 or 7.
  • Given an age, figure out whether someone's a baby, toddler, child, teenager, adult or old codger.
  • Calculate grades A-F based on final percentage score.
  • Given a number on the roulette table, figure out whether it's red/black, high/low and odd/even.
  • Given a blackjack hand, check if it's okay or bust (this is good since J/Q/K morph into 10). You could also figure out whether to draw another card (if total under 17 for example).

That's just a smattering of possibilities that you could get away with.

paxdiablo
Thanks. The leap year question is good. For TTT and guessing the number, don't we need some kind of a loop as well?
gphilip
@gphilip, ah, yes. I hadn't realised you wanted _just_ selection statements. I'll update the answer.
paxdiablo
paxdiablo, thanks for the smattering.
gphilip
+1  A: 

There are numerous of options here. Maybe let them build a simple calculator, taking into account division by zero, odd/even numbers and the like.

Edit: Found this simple excercise on if-else (in java) which can be transformed into Python.

BennySkogberg
+5  A: 

It's hard for those of use who have been programming for years to "get" what it feels like to start from nothing. I would steer clear of anything needing more than 5 lines of code.

You need to decide the order in which you cover things such as User Input, Output, if, else, while, for, file io etc.

When covering IF do they already know how to get some user input? Print some output? Code a FOR loop? Do arithmentic on integers? Determine whether a number is divisible by another number?

The answers to these questions constrains your examples for IF.

I'd suggest doing Output, Arithmentic, FOR, Divisibility (modulus), User Input before doing IF.

Then I can pose problems such as

Print the first 100 odd numbers
Determine the factors of a number entered  by the user
Play a number guessing game (User enters a guess, you print YES or Higher or Lower)
djna
djna, We have already covered how to get user input and print output. No loops yet. Integer arithmetic and divisibility test, yes. We will shortly cover one of the loops, and then I can use your suggestions. Thank you.
gphilip
you could use if/else to determine if a number entered is odd or even.
Wayne Werner
I do not know how student would take it but if I could decide schedule for teaching Python for newbies without preconceptions, I would be sure to fill in the pythonic list comprehension and try.. except..finally (with ZeroDivision error, when talking about arithmetic) first, then tell: If you need many lines of code with assignment here is this for..else, while..else, multiline if..elif..else to give you power to do so (maybe after they have learned making functions and learning that sort, max, min are ready and they do not need to do them themselves).
Tony Veijalainen
+1  A: 

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]
luc
luc, I'm afraid your answer is a bit over the head for me, not to say anything about my students :-)
gphilip
+1: Good points and example (@gphilip please learn what @luc suggests while you're teaching). Also, nice selection of songs! :-)
GreenMatt
I definitely second the list comprehension use. Do not teach reimplementing for loop by manual counter, when generally you should avoid the indexing style in Python altogether. Even my answer is purposely un-code-golf-like geared for clarity.
Tony Veijalainen
A: 

Once you make it to looping and/or functions, a great one would be "four is magic" - four is the only word with the same # of letters as the number, and supposedly all numbers converge to four. So the game goes something like this:

seventeen is nine
nine is four
four is magic

or (discounting spaces):

one hundred is ten
ten is three
three is five
five is four
four is magic

Of course if you just wanted to stick to if/else at the moment you could fairly easily do this for the numbers 0-10, and just have a series of 11 if...else blocks (1-5 and you'd need even less).

Wayne Werner
This is Code Golf: Four is magic http://stackoverflow.com/questions/3230978/code-golf-four-is-magic, the Pythos solutions for it including mine have not a single if-statement.
Tony Veijalainen
@Tony, that doesn't mean if/else logic is inappropriate. Heck, the most straight-forward solution practically begs for simple branching statements. Besides, code golf is *not* typical code (if it is, let me know where you work so I can avoid their products!). Of course code golf and the OPs desires are two entirely different things. And you've been programming long enough to know that you can approach any problem from a variety of different ways (functional, OOP, imperative, blah blah blah).
Wayne Werner
Most straight forward solution for me without code golf stuff is still dictionary lookup. Of course anything can program many ways, surely the problem would back track nicely in Prolog or you could make recursive algorithm with if ( if number is more than twenty ... if number == 4: print "Four is magic"). I was just worried that students would get in habit of using if .. elif when should. And I reversed the changes that somebody did to just make my solution shorter. It should be easily understandable (simple hex number lookup).
Tony Veijalainen
A: 

One of the best is Project Euler problem #1.

http://projecteuler.net/index.php?section=problems&amp;id=1

This requires considerable care to get the if-conditions exactly right.

S.Lott
A: 

I like the "Three men and a monkey on an island" problem:

Three men are stranded on a desert island with a monkey. They collect all of the coconuts and put them into a big pile. Then throughout the night each man gets up secretly and takes 1/3rd of the remaining pile and hides it. When he splits the pile into thirds there's 1 remaining which he gives to the monkey. Then in the morning after they all wake up they split the pile into 1/3rds ... with 1 left-over for the monkey. How many coconuts were in the pile originally?

The general strategy for solving this is to use a for-loop to check all numbers from 1-10,000 (or some other large number). You need to use if statements to check the remainder. You can later expand this problem to a more general word problem of X-men and Y-monkeys ... this requires a nested for-loop.

JudoWill
A: 

You could also prep your beginner programmers to pass the FizzBuzz test. Seeing how this is an extremely common filtering function for hiring programmers you could cite:

"After completing this assignment you are above 199 out of 200 programmers who apply to professional positions"

JudoWill