CMPT 120 Lab 7

This site applies only to CMPT 120 D1 (Burnaby) in Summer 2011. See the other instructors' pages for other sections.

In this lab, you will need to access the online Python reference. In CSIL, you may need to set your proxy settings properly to do this.

  1. Write a Python program that prints out the current weekday and time in this format:
    Saturday, 04:35 PM

    The time module contains a function strftime (“string format time”) that will format the current time. After you import the time module, this statement will print the current time in a different format

    print time.strftime("%b %d, %H:%M")

    Get that statement working first. Then use the online documentation to get the format as required above.

    [Note: do not name the file time.py. If you do, it will confuse the import time statement—it will try to import the file you just created, not the time module that you need.]

  2. Create a Python program that simulates rolling dice. These are standard dice: when rolled, they show number from 1 to 6, each randomly with equal probability.

    The random module contains functions that generate random values. In this problem, you need random integers from 1 to 6. When the program is run, it should look like this:

    How many dice? 3
    Die 1: 1
    Die 2: 5
    Die 3: 3
    How many dice? 4
    Die 1: 1
    Die 2: 1
    Die 3: 3
    Die 4: 6
  3. Strings in Python are actually objects and contain several methods that can operate on their contents. For example they contain a strip method:
    >>> s = "   a b c d       "
    >>> s.strip()
    'a b c d'

    Use the replace and upper methods, described in the String Methods Reference to display a string in all uppercase, and with the spaces replaced by underscores:

    Enter a string: A string I entered
    Uppercase:   A STRING I ENTERED
    Underscores: A_string_I_entered