Change Contents of the Bubble
Welcome to CS1315. Click on the python to add comments.

Looking for the book? They have it at the Engineer's Bookstore at 748 Marietta St NW. Here is there website: http://www.engrbookstore.com/ - Monica

Hotspots: Slides and CodeTA CornerComments?AnnouncementsFAQStatic Webspace
View this PageEdit this Page (locked)Uploads to this PageHistory of this PageHomeRecent ChangesSearchHelp Guide

Examples of how to use modules

# The area of a circle
def area(radius):
  import math                          # Not strictly necessary, because math is imported automatically
  return math.pi * radius ** 2   # Pi r squared

# Deal a hand of n cards
def dealHand(n):
  import random          # Import the functions from module random
  deck = range(1, 53)   # A fresh deck is cards 1..52 (where 1..13 are spades, etc.)
  random.shuffle(deck) # Shuffle the deck. I.e. randomize order of list elements
  return deck[0 : n]       # Return the first n of the shuffled deck

# Roll n (six-sided) dice
def rollDice(n):
  import random                                     # Import the functions from module random
  total = 0                                               # The total of the n dice
  for die in range(n):                                # Roll each die
    roll = int((random.random() * 6) + 1)  # The roll is between 1 and n inclusive but must be integer
    total = total + roll                               # Add this roll to the previous ones
  return total

# What day is it?
def todaysDay():
  import time              # Import the functions from module time
  now = time.ctime()   # Get the current time and date in string format
  return now[0:3]        # Day is the first three letters of the date string

# What year is it?
def thisYear():
  import time              # Import the functions from module time
  now = time.ctime()   # Get the current time and date in string format
  return now[-4:]         # Find last four digits. That's the year


Link to this Page