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 )
![]() | We've defined a function named |
![]() | The function called |
![]() | The |
![]() | The “main” part of this program is the for loop
at the bottom, which calls 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 |