Basic Python Programs


A Simple Program: dice

The program below simulates the roll of a pair of dice. The first line,

#!/usr/bin/env python

tells Unix to execute the program using the python interpreter. (Other OS's, such as Windows, merely treat this line as a comment.) It is important not to put a space after the "#" sign.

from whrandom import *

imports the code for the whrandom class. Whrandom is a more-fair pseudo-random number generator than the alternative, random, is.

ro = whrandom()

creates the "random number object" ro. We need ro because of its member functions that actually generate the random numbers.

die_1 = ro.randint(1, 6)

and

die_2 = ro.randint(1, 6)

call the randint function to get random integers between 1 and 6.

The program:

#!/usr/bin/env python
#file dice.py
#Simulates rolling of dice.
from whrandom import *
ro = whrandom()

die_1 = ro.randint(1, 6)
die_2 = ro.randint(1, 6)
dice = die_1 + die_2
print "The dice roll gave %d." % dice

A Harder Program: least common multiple

The problem: given two positive integers, compute their least common multiple.

The approach: Start with either number. Keep adding it to itself until the sum is a multiple of both original numbers.

Note that, in general, this is not a very efficient algorithm, although in the specific case where the numbers given are small (in the tens or lower), it probably is faster than most other algorithms for this problem. For large numbers, it would be best to compute the greatest common factor by the Euclidean Algorithm, divide the GCF into either number, and then multiply the quotient by the other number.

The code:

#!/usr/bin/env python
#file lcm.py

#Read two positive integers, and compute their least
#common multiple.

num = input("Enter two positive integers, separated by a comma: ")
sum = num[0];
while (sum % num[0] != 0) or (sum % num[1] != 0):
   sum = sum + num[0]
print "The least common multiple of %d and %d is %d." % (num + (sum,))


Next: Python Functions.

Go back to First Python Page.