Functions

Functions#

Questions#

  • Which value does hello_world() return?

def hello_world():
    print("Hello World")
  • what is the difference between hello_word and hello_world_string?

def hello_world_string():
    return "Hello World"
  • What is the type of hello_world_string and hello_world_string()?

  • Write a function with three arguments. Execute this function with different combinations of keyword and positional arguments. What is allowed, what is not? What rules can be derived from that result?

  • Write a function with two arguments. One should have a default value. At which position does it need to be placed in the signature?

  • Describe the behaviour of the following program. Change the code such that the function always returns the same data.

def append_element(e, l=[1]):
    l.append(e)
    return l

print(append_element(2))
print(append_element(2, [5]))
print(append_element(2))
print(append_element(2))
  • Of what type are the parameter args and kwargs in the following function?

def func_pos_args(*args, **kwargs):
    print(args, kwargs)
  • Read PEP257 (you can skip the last section on handlin indentation in docstrings) and write a proper docstring for the function append_element from above.

  • Swap the order of instructions in the body of the function below. What happens?

s3 = "I hate {}"
def f(city):
    s3 = "I love {}"
    print(s3.format(city))
    
f('Paris')
print(s3.format('Paris'))

Coding exercise#

Write a function which checks, if a coordinate tuple lies within a circle with centre M and radius r (in 2D). Don’t forget the docstring!