Lecture 10 - Exercises

10A - Defining Functions

  1. Which of the following is/are true of the print function?

    1. It does not take inputs (arguments)
    2. It does not return a value
    3. It does not have any effects
    4. Using it requires understanding the code that implements
  2. You’ve seen the len function a couple times now. Describe its behavior in terms of its inputs, effects, and return value.

  3. Which of the following programs will not cause an error when run?

    1.    def greet():
           print("Hi there!")
         greet()
    2.    def greet():
           print("Hi there!")
    3.    greet()
         def greet():
              print("Hi there!")
    4.    def greet:
           print("Hi there!")
         greet()

10B - Passing inputs to functions

Consider the following program:

def h2m(hours, minutes):
  total_mins = 60 * hours + minutes
  return total_mins

arg1 = int(sys.argv[1])
arg2 = int(sys.argv[2])

print(h2m(arg1, arg2))
  1. Suppose the program is run with two command line arguments and prints 80. If the first command line argument was 1, what must the second one have been?
  2. Suppose the program is run with two command line arguments and prints 80. If you don’t know anything about either command line argument, how many possible pairs of numbers could have been given as command line arguments?

Consider the following program:

def pnmr(n, r):
    print(n % r, end=" ")

size = 7
rad = 3
for num in range(0,size):
    pnmr(num, rad)
  1. How many numbers does this program print? Count total number printed, not digits or unique numbers.
  2. How many times does the program print the number 1?