Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Some Examples

Here's a big example of using the odd, spinWheel and report functions.

Example 9.1. functions.py

#!/usr/bin/env python
import random

def odd( spin ):
    """odd(number) -> boolean."""
    return spin%2 == 1
    
def report( spin ):
    """Reports the current spin on standard output.  Spin is a String"""
    if int(spin) == 0:
        print "zero"
        return
    if odd(int(spin)):
        print spin, "odd"
        return
    print spin, "even"
    
def spinWheel():
    """Returns a string result from a roulette wheel spin."""
    t= random.randrange(38)
    if t == 37:
        return "00"
    return str(t)
    
for i in range(12):
    n= spinWheel()
    report( n )
1

We've defined a function named odd. This function evaluates a simple expression; it returns True if the value of it's parameter, spin , is odd.

2

The function called report uses the odd function to print a line that describes the value of the parameter, spin . Note that the parameter is private to the function, so this use of the variable name spin is technically distinct from the use in the odd function. However, since the report function provides the value of spin to the odd function, their two variables often happen to have the same value.

3

The spinWheel function creates a random number and returns the value as a string.

4

The “main” part of this program is the for loop at the bottom, which calls spinWheel, and then report. The spinWheel function uses random.randrange; the report function uses the odd function. This generates and reports on a dozen spins of the wheel.

For most of our exercises, this free-floating main script is acceptable. When we cover modules, in Part IV, “Components, Modules and Packages”, we'll need to change our approach slightly to something like the following.

def main():
    for i in range(12):
        n= spinWheel()
        report( n )
        
main()

This makes the main operation of the script clear by packaging it as a function. Then the only free-floating statement in the script is the call to main.


 
 
  Published under the terms of the Open Publication License Design by Interspire