# The primary purpose of the fizzbuzz program is to demonstrate # how the programming language handles conditional statements # and looping constructs. def isfizz(num): """Returns true if the given number is divisble by 3""" return num % 3 == 0 def isbuzz(num): """Returns true if the given number is divisble by 5""" return num % 5 == 0 def fizzbuzzSingle(num): """This follows the fairly simple pattern of generating a single instance of fizz buzz depending on the number value given.""" # In a function definition, if the first line is a triple quoted string, # then it's the primary comment describing that function, it will automatically # be used to generate the documentation made with pydoc. # for simplicity, we'll only include numbers that are great than 0, # and by definition they must be integers. Intergers > 0 are natural numbers. assert num > 0, "The given number " + str(num) + " is not a natural number." # if either of the assertions above fail, then an assertion error is thrown with # the text given as an error message. if isfizz(num) and isbuzz(num): return "fizzbuzz" elif isfizz(num): return "fizz" elif isbuzz(num): return "buzz" else: # Python doesn't use implicit type casting, so if you need to # convert from one type to another (in this case int to string) # you have to do so manually as below. return str(num) def fizzbuzzComprehension(topNum): """Rather than use explicit looping or recursion here, I've opted for using the fairly unique feature of python called list comprehention. It's fairly similar to the list construction syntax used in set theory.""" fizzbuzzList = [fizzbuzzSingle(num) for num in range(1, topNum + 1)] return " ".join(fizzbuzzList) def fizzbuzzFor(topNum): """Here I've used the more common for loop to generate the fizzbuzz string, It's less concise than the list comprehension version, but is also less suprising to those who aren't as familiar with the syntax.""" fizzbuzzString = "" # Range generates a list of numbers from the first value to the number preceding # the second value. for num in range(1, topNum + 1): fizzbuzzString += fizzbuzzSingle(num) + " " # Three important points about Python strings and array's. # 1. Strings are treated as an array of single character strings. # 2. Sub-arrays are selected via slice notation ([Int1:Int2]) where the # Int1 is the first value in the sub-array and Int2 is the value following the # last value. If either value is left out, then it starts/ends at the start/end # the list. # 3. Python's array syntax is unusual in that, along with specifying a normal range # counting from the first character (at index 0) you can also include negative # indices. Negative indices count starting at the end of the list. # Examples: # "spam"[0:1] = "s" # "spam"[:3] = "spa" # "spam"[-2:] = "am" # "spam"[:-1] = "spa" # Return the total string, dropping the last space. return fizzbuzzString[:-1] if __name__ == "__main__": print fizzbuzzComprehension(20)