Functions
Functions
Learning outcomes
- What functions are and how to define them
- What is a DRY principle?
- How to invoke functions?
- How to return values?
- How to specify function parameters?
- What are default parameters?
- What is a variable scope in Python?
Learning material
Watch these two videos on functions:
Knowledge check
- What is the
def
keyword used for? - What keyword lets you give back the result of a function?
- How to specify default parameters?
- How to deal with the unknown number of function parameters?
- What is the LEGB rule?
- What two keywords help you change the score of a variable?
Exercises
- Define a function that prints a string that you pass in it as a parameter, and call it 5 times using a loop.
- Create a function
calculator
that takes three arguments: 2 numbers and a string. The string's value can be one of the 4 values:add
,substract
,multiply
, ordivide
. Return a result of an operation that corresponds to the string. (Use Python'sswitch
statement, about which you can read more here). Don't forget to put adefault
case that displays a meaningful message. - Make a function that prints out some message. Define the second function that takes a function as a parameter. Call the second function and pass first function as a parameter.
- Solve a Fibonacci Number problem. Here's the problem formulation on LeetCode.