[Courses] [python] Lesson 5: Infinite loops, modulo, and random numbers

Peggy Russell prusselltechgroup at gmail.com
Thu Jul 21 02:31:51 UTC 2011


> ====================== Homework =============================
> 
> 1. Suppose you have a list of colors, like 
>    colors = [ "red", "orange", "yellow", "green", "blue" ]
>    ... How would you use the modulo operator, %, to step through the colors 
>    in order, printing out one after another and going back to red after blue?
things = 20
colors = [ "red", "orange", "yellow", "green", "blue" ]

print("Color {0} things with {1} colors{2}{3}".format(things, len(colors), "\n" , "-"*29))
for i in range(0, things):
  print("{0:2d} {1}".format(i, colors[i % len(colors)]))


> 2. How would you write a program to choose a random file from a
>    directory full of files? Assume the directory is in some fixed place,

import os         # http://docs.python.org/library/os.path.html
import random     # http://docs.python.org/library/random.html
import pwd        # http://docs.python.org/library/pwd.html#module-pwd

dir = "/usr/local/doc"

while True:
  file = random.choice(os.listdir(dir))
  if os.path.isfile(os.path.join(dir, file)):
    print('\nRandom file "{0}" in directory "{1}"'.format(file, dir))
    st = os.stat(os.path.join(dir, file))
    print("Size: {0} bytes Name/uid: {1}/{2}".format(st.st_size, 
                                                     pwd.getpwuid(st.st_uid).pw_name, 
                                                     st.st_uid))
  else:
    print('\nNot a file - "{0}"'.format(file))

  if not (input("Try again [Y|N]: ").lower().startswith('y')):
    break

> 3. Make a list of nouns and a list of verbs. Then write a program that
>    makes a random sentence by choosing a random noun and a random verb.

import random

noun='''Poet Harmony Farmer Painter Tailor Miner Reporter Barber Doctor'''.split()
verb='''reads plays plants draws sews digs writes cuts heals'''.split()

while True:
  print(random.choice(noun), random.choice(verb) + ".")
  if not (input("Try again [Y|N]: ").lower().startswith('y')):
    break

Peggy


More information about the Courses mailing list