Practice Problems 7 Solutions

  1. If you had the following code in a file named

    if __name__ == "__main__":
        print("This is a test, it is only a test.")
        print("This is a test of: " + __name__)

    What would be printed in the console if you:

    1. Ran the program, e.g. via the “green arrow” in Thonny

      This is a test, it is only a test

    2. Typed “import test” into the console

      This is a test of: test

    Recall that when we run with the green arrow __name__ is "__main__" and when the file is imported, __name__ is set to the name of the file without the “.py” at the end.

  2. For program with the following usage message, what will be the length of sys.argv when the user supplies the correct number of command-line arguments.

     usage: python3 <input file> <output file> <hours>

    The program takes 3 arguments so len(sys.argv) should be 4 (the first entry is always the program name).

  3. You’re planning on writing a program that can take one or more files as command-line arguments and will do something with each file (for example, print the contents).

    1. Write the portion of the program that ensures that whenever this program is executed with the wrong number of parameters, it prints out the usage of the program:

       $ python3
       usage: python3 <file1> <file2> ...
    2. To get started, write code such that if the user does enter one or more files, the program prints out the name of each of the files entered:

       $ python3 some_file another_file and_another_file
     import sys
     if __name__ == "__main__":
         if len(sys.argv) <= 1:
             print("usage: python3 <file1> <file2> ...")
            # Print out the names of all the entered files, but
            # don't print out the item at index 0, since it's the program name
            for f in sys.argv[1:]:
  4. The following code prints out two variables separated by a comma (",") and followed by a blank line. Rewrite this code more concisely using the print function’s optional arguments.

     print(str(key) + "," + str(value))

    We use the sep and end arguments to accomplish the above with a single print statement. We are taking advantage of the fact that print can take a variable number of positional arguments.

     print(str(key), str(value), sep=",", end="\n\n")

    We can make this even more concise by taking advantage of the fact that print automatically converts its arguments to strings.

     print(key, value, sep=",", end="\n\n")
  5. Consider the following program in a file name “”.

     import sys
     print(sys.argv[0], sys.argv[int(sys.argv[1])])

    What will be printed when this program is invoked as:

    1. python3 0 a b c 
    2. python3 2 a b c a 
    3. python3 1 a b c 1
  6. This is the docstring for the get method on dictionaries.

         D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.

    The second argument for get is optional, e.g. { 1: 2}.get(5) evaluates to None. Implement a function named my_get as a replacement for get (without using get). Your function should take a dictionary, a key and an optional value as parameters and return the same result as get.

     def my_get(dictionary, key, value=None):
         if key in dictionary:
             return dictionary[key]
             return value
  7. Writing a program that could take one or two command-line arguments. If the second argument is not present, the value should default to 12. For testing purposes, just print the two values used by the program. For example:

     $ python3 test.txt
     $ python3 test.txt 5
     if __name__ == "__main__":
         # Print the first command line argument
         # Use the second command line parameter or the default value
         if len(sys.argv) == 3:
             value = sys.argv[2]
             value = 12