开发者

What are good programming questions to exercise the use of "if ... else" in Python?

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 n开发者_运维问答ot 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).


It's hard for those of us 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)


"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.


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.


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.


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]


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.


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).


One of the best is Project Euler problem #1.

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

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


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.


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"


At my lecture I asked them to implement is_between_5_8(x) (I admit, there's no ulterior motive with using 5 and 8), and afterward I gave them the exercises to implement abs(x) and closest_to_zero(x, y).

If you've taught them recursion I can give you a few more suggestions :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜