Functions Worksheet

Back to Week 3 Notes

Functions and Calls

We’re writing functions now, so be mindful of the need for function calls. If you run a program that defines a function and doesn’t call it, you won’t get any output!

The tests always include a function call (which is how we test your definition).

Problem 1

Write a function hello_world that prints hello world! when called.

def test():
  """
  >>> hello_world()
  hello world!
  """
import doctest
doctest.testmod()

Problem 2

Write a function multi_line that prints:

print
on
several
lines

when called.

def multi_line():
  return
import doctest

def test():
  """
  >>> multi_line()
  print
  on
  several
  lines
  """
  return

doctest.testmod()

Problem 3

Write a function one that prints output from function one.

Write a second function, two that calls function one twice.

def ok():
  okk()

def okk():
  print(123)
import doctest

def test():
  """
  >>> one()
  output from function one
  >>> two()
  output from function one
  output from function one
  """
  return

doctest.testmod()

Problem 4

Write a function four that takes an integer argument and prints out the argument multiplied by 4.

def four(x):
  # your code here
import doctest

def test():
  """
  >>> four(1)
  4
  >>> four(3)
  12
  >>> print(four(1)) # will fail if returning instead of printing
  4
  None
  """
  return

doctest.testmod()

Problem 5

Write a function return_four that takes an integer argument and returns the argument multiplied by 4.

def return_four(x):
  # your code here
assert return_four(2) == 8
assert return_four(3) == 12

Problem 6

Write a function repeater that takes a positive integer argument and “repeats” the integer, returning in a new int:

  • repeater(5) returns int 55
  • repeater(10) returns int 1010
  • repeater(200) returns int 200200

You’ll need to use the int and str functions to convert between int and string.

def repeater(z):
  # your code here
assert repeater(2) == 22
assert repeater(12) == 1212
assert repeater(0) == 00
assert repeater(150) == 150150

Back to Week 3 Notes