From 531f790c2f93e81705c7bcdc004a93c8a11c02d7 Mon Sep 17 00:00:00 2001 From: waldek Date: Fri, 29 Oct 2021 14:37:52 +0200 Subject: [PATCH] completes functions --- learning_python3.md | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/learning_python3.md b/learning_python3.md index 9f4e7fe..b08bb98 100644 --- a/learning_python3.md +++ b/learning_python3.md @@ -627,7 +627,7 @@ This will give an `UnboundLocalError: local variable 'name' referenced before as name = "Wouter" def function_scope(): - print("inside the function", name) + print("inside the function", name) name = "Alice" @@ -653,12 +653,32 @@ print("outside the function", name) ## Functions that *return* something -TODO basic math functions +While the `global` keyword can be useful, it's rarely used. +This is because function can not only *do* thing, they can **return** objects. +The `input` function we've been using is a prime example of this as it always give you a `str` object back with the content of the user input. +We can copy this behaviour as follows. + +```python3 +def square_surface(length, width): + surface = length * width + return surface + + +square = square_surface(20, 40) +print(square) +``` + +🏃 Try it +--- + +Functions that return an object are essential to any modern programming language. +Think of some calculations such as the Celsius to Fahrenheit converter and create the corresponding functions. ## Some links to read up on * some [best practices](https://able.bio/rhett/python-functions-and-best-practices--78aclaa) for functions * more details on [variable scope](https://pythongeeks.org/python-variable-scope/) +* in depth [article](https://realpython.com/python-return-statement/) on return values in python # Coding challenge - Pretty Print @@ -675,6 +695,8 @@ Kind of like the two examples below. ################# ``` +As an extra challenge you could return a [multi line string](https://www.askpython.com/python/string/python-multiline-strings) and print it outside of the function! +
Spoiler warning