Practice Problems 7 Complete before class on 2022-11-04

Complete the following problems on paper. Try to solve each problem on paper first before using Thonny to confirm your answers.

  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
    2. Typed “import test” into the console
  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>
  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
  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))
  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
    3. python3 1 a b c
  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.

  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