class: big, middle # Engineering 1020: Introduction to Programming .title[ .lecture[Lecture 23:] .title[Recursion] ] .footer[[/lecture/23/](/lecture/23/)] --- # Let's finish up functions! ## Recall: ### Keyword arguments ### Default arguments -- ## Today: ### Recursion --- # Recall: keyword arguments ### Using the colour LCD screen: ```python rgb_lcd_colour(255, 0, 255) ``` (aside: what colour is this?) ### Easier to tell now: ```python rgb_lcd_colour(red=255, green=0, blue=255) ``` No _positional_ arguments after the first _keyword_ argument --- # Recall: default arguments .floatright[ ```python def get_user_input(prompt='Input? '): return input(prompt) ``` ] Passed to the parameter if no argument in the call #### One way to print: ```python print('these', 'words', 'go', 'on', 'one', 'line') print('these', 'words', 'go', 'on', 'the', 'next', 'line') ``` #### Another way: ```python print(1, 2, 3, sep='*', end=' + ') print(4, 5, 6, sep='*') ``` --- # Recursion -- ### A function calling itself (??) ??? There are lots of interesting problems in computing whose solutions can be expressed most elegantly via a recursive function. We won't require you to write a lot of those — that's more for a Data Structures and Algorithms course in Term 4 — but you do need to be at least somewhat familiar with the concept of recursion. It's an elegant tool, but like a lot of interesting concepts, it has subtleties to be aware of. -- ```python def factorial(n): return n * factorial(n-1) ``` -- * each **call** has its own variables -- * beware of **infinite recursion** (as in the example above!) ??? Like a loop with a perpetually-true condition, recursion can lead to a program that never stops running (at least until it runs out of memory for all of the function calls' memory!). -- * need a **base case**: when do we stop recursing? ??? A **base case** for recursion is when the recursion **stops**. In the example of a factorial, the factorial is actually defined in two parts: $$ n! = n \times (n-1)!~\Big\vert~n > 0 $$ $$ 0! = 1 $$ </div> The base case for our factorial function, therefore, is that **when `n` is 0, `factorial` should return 1**. --- # Problems ## Let's work on some problems! --- # Summary ### More fun with functions: * Special arguments: * keyword arguments * default arguments * Recursion --- class: big, middle (here endeth the lesson)