#!/usr/bin/python from random import * #define a few functions def IsPalindrome(a): length = len(a) start = 0 end = length-1 while start < length/2: if a[start] != a[end]: return False start += 1 end -= 1; return True def TestWord (word): if IsPalindrome(word): print word, " is a palindrome" else: print word, " is not a palindrome" # the main program begins here. # a simple greeting print("Hello World") print # print some letters for letter in "abcdefg": print letter print # print some numbers i = 0; while (i < 10) : print (i) i += 1 print # can we do a conversion to binary num = 35 value = "" while num > 1: value = str(num % 2) + value num = num / 2 if num == 1: value = str(num) + value print "35 = ", value print # call some functions TestWord("racecar") TestWord("abba") TestWord("able was I ere I saw elba") TestWord("bad") print # strings print 'hello is "hi" in other places' print "but 'hi' is also hello sometimes" print "\tAnd all of the \a's and whistles work too \n\n\t\t\tSee!" print print "Cooking a bit of pi" TRIALS = 100000 hits = 0 i = 0 while i < TRIALS: x = uniform(0,1) y = uniform(0,1) if x*x + y*y < 1.0: hits += 1 i+= 1 print "pi is about ", 4.0*float(hits)/float(TRIALS) print print "Or Pi from my hero Leibniz" i = 3 pi = 1.0 sign = -1.0 while i < TRIALS: pi += sign * 1.0/float(i) i += 2 sign *= -1 print 4.0*pi # a range: print range(10) print range(1,10) print range(1,10,3) # another pi compuatation pi = 1 sign = -1.0 for i in range(3,TRIALS,2): pi += sign * 1.0/float(i) sign *= -1 print 4.0*pi