# There is more than one way to accomplish a task. # I needed a method to countdown from a positive # number down to 0. Here are three ways to solve # the issue. Of course there are many more possible # solutions. # # I'd like to title this post "The Final Count Down" # Listen to this tune whilst perusing the script: # www.youtube.com/watch?v=tt_ro2aerQg # Using recursion always makes the girls swoon. def recursiveCountdown(number): print number if number > 0: recursiveCountdown(number-1) # Old school while loop. This solution gets points # for being the most obvious. def whileLoopCountdown(number): while number > -1: print number number -= 1 # Using python's xrange function is the most concise. def xrangeCountdown(number): for i in xrange(number, -1, -1): print i print "It's the final countdown" number = input("Enter number: ") print "Recursive..." recursiveCountdown(number) print "While Loop..." whileLoopCountdown(number) print "xrange..." xrangeCountdown(number) # my output: # #It's the final countdown #Enter number: 5 #Recursive... #5 #4 #3 #2 #1 #0 #While Loop... #5 #4 #3 #2 #1 #0 #xrange... #5 #4 #3 #2 #1 #0
A python example based blog that shows how to accomplish python goals and how to correct python errors.
Thursday, February 25, 2010
Python - the final countdown
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment