Functions Flashcards
Why use functions in python?
They allow us to encapsulate logic in our code.
How do you specify default arguments in functions?
def func(def_arg = value)
Why shouldn’t you use mutable default arguments in python?
It changes the result of a function at each call.
Explain how *args and **kwargs work in python, give an example of when they might be useful
- args : allow an arbitrary number of positional arguments
* *kwargs : allow an arbitrary number of key-word args.
What comes first, positional arguments or default arguments?
positional then default
What does it mean to say that a function has side effects? Why are they not recommended?
Side effects are where calling the function mutates their inputs or other parts of the programme. This can be a source of bugs.
When a function is executed, a namespace is created, what is inside this namespace?
All variables/function parameters defined within the function.
How would you modify global variables inside a function?
global
… code …
Briefly explain what a decorator does, what are its inputs and outputs?
A decorator modifies a function at run time. It takes a function as input, and outputs a modified version.
Give an example of when a decorator might be useful
It allows the modification of one isntance of calling the function, without which you would have to define multiple similar functions.
Explain what a generator is? Which keyword do they use? How can it be useful?
for …:
… code …
yield x
Useful since each element of the sequence isn’t stored, only calculated at each iteration.
How do you iterate over a generator?
for i in :
… code …
to get the next in sequence: next()
Write a list comprehension using an if-else statement
[x ** 2 for x in range(100) if x%2 == 0 else x ** x]
Write a list comprehension using a lambda function
[(lambda x : x**2)(x) for x in range(100)]
How do list comprehensions differ from generator comprehension? What is the difference in syntax?
list comprehensions are performed all at once, generator comprehensions are performed at each iteration.
[list comp]
(generator comp)