completes functions
This commit is contained in:
parent
e05b67be6a
commit
531f790c2f
|
@ -627,7 +627,7 @@ This will give an `UnboundLocalError: local variable 'name' referenced before as
|
||||||
name = "Wouter"
|
name = "Wouter"
|
||||||
|
|
||||||
def function_scope():
|
def function_scope():
|
||||||
print("inside the function", name)
|
print("inside the function", name)
|
||||||
name = "Alice"
|
name = "Alice"
|
||||||
|
|
||||||
|
|
||||||
|
@ -653,12 +653,32 @@ print("outside the function", name)
|
||||||
|
|
||||||
## Functions that *return* something
|
## 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 links to read up on
|
||||||
|
|
||||||
* some [best practices](https://able.bio/rhett/python-functions-and-best-practices--78aclaa) for functions
|
* 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/)
|
* 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
|
# 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!
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>Spoiler warning</summary>
|
<summary>Spoiler warning</summary>
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue