Functions Worksheet
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():
returnimport 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 hereimport 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 hereassert return_four(2) == 8
assert return_four(3) == 12Problem 6
Write a function repeater that takes a positive integer argument and “repeats” the integer, returning in a new int:
repeater(5)returns int55repeater(10)returns int1010repeater(200)returns int200200
You’ll need to use the int and str functions to convert between int and string.
def repeater(z):
# your code hereassert repeater(2) == 22
assert repeater(12) == 1212
assert repeater(0) == 00
assert repeater(150) == 150150