Sunday, June 28, 2009

Interesting Python Functions

This post will contain a collection of Python library functions that I found interesting. I will keep adding to the collection as I encounter more interesting functions.

#----------------------------------------------------------------------------
# range() - this function generates a list of numbers
#----------------------------------------------------------------------------

upperBound = 5
range(upperBound) # this generates [0, 1, 2, 3, 4]

lowerBound = 2
range(lowerBound, upperBound) # this generates [2, 3, 4]
range(1, 11, 3) # generates [1, 4, 7, 10].
# range(lowerbound, uppperbound, step)

# an example of range() in action
monthList = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
for i in range(12):
print monthList[i], # prints all the months of the year

#-----------------------------------------------------------------------------------------
# randrange() - generates a random number from a range of numbers
#-----------------------------------------------------------------------------------------

import random # this module is required to use randrange()
random.randrange(6) # generates a random number between 0 to 5 inclusive
random.range(6) + 1 # generates a random number between 1 to 6 inclusive

#--------------------------------------------------------------------------------
# choice() - returns a random element from a sequence
#--------------------------------------------------------------------------------

vowels = ('a','e','i','o','u')
osList = ["linux", "BSD", "UNIX", "NT", "Solaris"]
random.choice(vowels) # randomly selects a vowel
random.choice(osList) # randomly selects an os


No comments:

Post a Comment