Complete the following problems on paper. Try to solve each problem on paper first before using Thonny to confirm your answers.
If you had the following code in a file named test.py
:
if __name__ == "__main__":
print("This is a test, it is only a test.")
else:
print("This is a test of: " + __name__)
What would be printed in the console if you:
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 time_shift.py <input file> <output file> <hours>
You’re planning on writing a program print_files.py
that can take one or
more files as command-line arguments and will do something with each file
(for example, print the contents).
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 print_files.py
usage: python3 print_files.py <file1> <file2> ...
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 print_files.py some_file another_file and_another_file
some_file
another_file
and_another_file
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))
print()
Consider the following program in a file name “test.py”.
import sys
print(sys.argv[0], sys.argv[int(sys.argv[1])])
What will be printed when this program is invoked as:
python3 test.py 0 a b c
python3 test.py 2 a b c
python3 test.py 1 a b c
This is the docstring for the get
method on dictionaries.
get(...)
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
.
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.py test.txt
test.txt
12
$ python3 test.py test.txt 5
test.txt
5