adds functions

This commit is contained in:
waldek 2021-10-29 12:08:01 +02:00
parent c74462e082
commit 6c65fe7156
1 changed files with 140 additions and 3 deletions

View File

@ -307,6 +307,8 @@ else:
print("you are at a dangerous crossroad in life!")
```
⛑ **Do not fight the automatic indentation in your IDE! Pycharm is intelligent enough to know when to indent so if it does not indent by itself, you probably made a syntax error.**
## Class string methods
Let's take the logic above and implement it in a real program.
@ -423,10 +425,12 @@ else:
We can use conditional logic to create quite elaborate decision processes.
Let's build a mini text based adventure game.
Granted it's not a *tripple A* game but it will train your `if` and `else` skills plus it will highlight some issues we'll overcome in the next section.
Consider the diagram below.
![adventure game](./assets/text_based_adventure_game.png)
Consider the diagram above we can imagine a program that functions nicely with the code below.
It is not very *readable* nor *scalable*.
```python3
answer = input("You're at a cross section. Do you go left or right?")
if answer.startswith("l"):
@ -475,12 +479,108 @@ else:
exit(0)
```
I urge you to read up on some [best practices](https://www.tutorialdocs.com/article/python-conditional-statements-tips.html) for `if` statements.
We will not improve on this particular example but I do advise you to create a similar style game during one of the workshops once we have learned some new tricks.
# Creating your own functions
One of the *issues* we have in the text based game example is duplicate code.
At two spots we execute almost identical code and this is something that should be avoided at all costs!
Why write the same thing over and over?
You're better off writing it **once** and use it **lots**.
This is where **functions** come into play.
Python ships with a lot of built-in functions but we can create our own very easily.
The keyword to define a function in python is `def`.
All the code that is *indented* will be executed when we **call** the function.
Here is a basic abstraction of correct syntax.
```python3
def first_function():
print("I'm a function")
print("Hear me roar!")
```
If you type *only* the code above in a new script, and run it, you won't see much.
This is because you only **created** the function.
To use it you need to **call** it.
This is done as follows.
```python3
def first_function():
print("I'm a function")
print("Hear me roar!")
first_function()
```
Learning how to create functions is a big step in your programming journey.
It can seem confusing at first because the code execution *appears* to jump around.
This is however **not** the case.
Your script is still read and executed **line by line** so you can not call a function **before** you defined it!
For now you should not overthink the structure of you scripts.
As long as they work you should be happy.
We'll dive into the proper *anatomy* of a program real soon.
## Functions that *do* something
TODO recipe with variable flavor (chocolate, vanilla, ...)
TODO pretty_print
The first function I showed you above performs a series of actions each time it is called.
We can use it to *bake cakes* for example.
Below we create **one** function to bake the cake, and call it **three** times to bake three cakes.
```python3
def bake_chocolate_cake():
print("mix the base ingredients")
print("add the chocolate flavour")
print("put in the oven")
print("enjoy!")
bake_chocolate_cake()
bake_chocolate_cake()
bake_chocolate_cake()
```
Now, you might like a *vanilla* cake from time to time.
Easy, we'll just write a second function for that purpose.
```python3
def bake_chocolate_cake():
print("mix the base ingredients")
print("add the chocolate flavour")
print("put in the oven")
print("enjoy!")
def bake_vanilla_cake():
print("mix the base ingredients")
print("add the vanilla flavour")
print("put in the oven")
print("enjoy!")
bake_chocolate_cake()
bake_chocolate_cake()
bake_vanilla_cake()
bake_chocolate_cake()
bake_vanilla_cake()
```
Voila, we can now make as many chocolate and vanilla cakes as we want!
But what about *bananas*?
Following our logic we can create a *third* function to bake a banana cake but you're probably seeing a *pattern* here.
Each `bake_FLAVOR_cake` function is almost identical, just for the flavoring.
We can create one generic `bake_cake` function and just add the custom flavor each time we actually *bake* a cake.
This is done with arguments.
```python3
def bake_cake(flavor):
print("mix the base ingredients")
print("add the {} flavor".format(flavor))
print("put in the oven")
print("enjoy!")
bake_cake("chocolate")
bake_cake("vanilla")
bake_cake("banana")
```
## Variable scope
@ -488,6 +588,43 @@ TODO pretty_print
TODO basic math 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/)
# Coding challenge - Pretty Print
Can you write me a function that decorates a name or message with a *pretty* character.
Kind of like the two examples below.
```
##########
# Wouter #
##########
#################
# Python rules! #
#################
```
<details>
<summary>Spoiler warning</summary>
```python3
def pretty_print(msg, decorator="#"):
line_len = len(msg) + (len(decorator) * 2) + 2
print(decorator * line_len)
print("{} {} {}".format(decorator, msg, decorator))
print(decorator * line_len)
pretty_print("Wouter")
pretty_print("Python rules!")
pretty_print("Alice", "-")
```
</details>
# Using the standard library
TODO import random exercise (digital dice)