Add lesson 5: Functions: name it once, use it everywhere
3 changed files with 37 additions and 0 deletions
lessons/05-functions-name-it-once-use-it-everywhere/README.md ADDED
| @@ -0,0 +1,19 @@ | ||
| 1 | +# Lesson 5: Functions: name it once, use it everywhere | |
| 2 | + | |
| 3 | +This lesson covers functions: name it once, use it everywhere. You'll read a short explanation, try three small exercises and finish with a quiz. | |
| 4 | + | |
| 5 | +Full lesson: [https://glibcode.net/courses/python-basics/lessons/5](https://glibcode.net/courses/python-basics/lessons/5) | |
| 6 | + | |
| 7 | +## Files | |
| 8 | + | |
| 9 | +- `functions.py`: defining functions, arguments and return values | |
| 10 | + | |
| 11 | +## Run it | |
| 12 | + | |
| 13 | +```sh | |
| 14 | +python3 functions.py | |
| 15 | +``` | |
| 16 | + | |
| 17 | +## Exercises | |
| 18 | + | |
| 19 | +See [exercises.md](exercises.md). Ask in the forum once you've tried. | |
lessons/05-functions-name-it-once-use-it-everywhere/exercises.md ADDED
| @@ -0,0 +1,5 @@ | ||
| 1 | +# Exercises: lesson 5 | |
| 2 | + | |
| 3 | +1. Find one thing in `functions.py` you could name better and rename it everywhere. | |
| 4 | +2. Add a comment above each block explaining what it does, in your own words. | |
| 5 | +3. Make the example ask for its input instead of using a fixed value. | |
lessons/05-functions-name-it-once-use-it-everywhere/functions.py ADDED
| @@ -0,0 +1,13 @@ | ||
| 1 | +def fahrenheit(celsius): | |
| 2 | + """Convert a temperature to Fahrenheit.""" | |
| 3 | + return celsius * 9 / 5 + 32 | |
| 4 | + | |
| 5 | + | |
| 6 | +def describe(celsius, unit="F"): | |
| 7 | + if unit == "F": | |
| 8 | + return f"{celsius} °C is {fahrenheit(celsius):.1f} °F" | |
| 9 | + return f"{celsius} °C" | |
| 10 | + | |
| 11 | + | |
| 12 | +for c in (0, 21, 37, 100): | |
| 13 | + print(describe(c)) | |