next up previous
Next: About this document ...

  1. Assuming that the current working directory is traxus, on my unix account, give the computed output:

          1 import os
          2 import string
          3 print 5/2
          4 str = "this.that"
          5 print str[-2]
          6 print os.getcwd()
          7 L = string.split(str, '.')
          8 print L
          9 print len(L)
    ****************************** OUTPUT ****************************** 
    2
    a
    /home/malloy/teach/372/quiz/2/code
    ['this', 'that']
    2
    ********************************************************************
    

  2. The raw_input command accepts a prompt and then reads a string from the keyboard. Complete the python program below so that it uses a loop to print the word that is entered backwards:

           word = raw_input("Type a word:  ")
           print word
    ****************************** ANSWER ****************************** 
          1 def backwards(w, n):
          2    if n <= len(w)-1:
          3      ch = w[n]
          4      backwards(w, n+1)
          5      print ch
          6
          7 if __name__ == "__main__":
          8    word = raw_input("Type a word: ")
          9    backwards(word, 0)
    ********************************************************************
    










  3. Write a program that receives two arguments from the command line and prints the sum of these two arguments. Include in your program some code that makes sure that the user inputs two arguments from the command line; if not, print a usage message and terminate the program.

    ****************************** ANSWER ****************************** 
          1 import sys
          2
          3 if __name__ == "__main__":
          4   if len(sys.argv) != 3:
          5     print "usage: ", sys.argv[0], " <arg1> <arg2>"
          6     sys.exit()
          7   arg1 = int(sys.argv[1])
          8   arg2 = int(sys.argv[2])
          9   print "The sum of %d + %d = %d" % (arg1, arg2, arg1+arg2)
    ********************************************************************
    











  4. Write a python program that prompts the user for a number, and then using a recursive function prints the factorial of that number.

    ****************************** ANSWER ****************************** 
          1 def fact(n):
          2     if n == 1: return 1
          3     else: return n*fact(n-1)
          4
          5 if __name__ == "__main__":
          6    print fact(5)
    ********************************************************************
    





Brian Malloy 2006-05-31