alphaPlan · Programming in a Data World · Cheat-sheet 02
Reusable code
Package work into named functions, build bigger programs from small parts, and hold many values in one list.
Ideas to remember
- 01A function is a small, named piece of a program that solves one specific sub-problem, and you reuse it by calling its name.
- 02Defining a function does not run it; the code inside runs only when you call it.
- 03A variable created inside a function is local to it and is gone when the function finishes; a value travels out through return.
- 04Modular thinking is build small, then combine: draw_house only calls draw_square and draw_triangle and repeats no drawing code.
- 05import brings in a ready-made collection of functions, and a module is nothing more than a Python file.
- 06A list keeps many values in one ordered container, and Python counts positions from 0, not from 1.
Words
- def add(a, b):
- Defines a function named add with two arguments; return a + b hands the sum back to whoever called it.
- draw_shape(length, num_sides)
- Draws a regular polygon; the turtle turns 360 / num_sides degrees at each corner.
- import turtle
- Loads all the drawing functions, so turtle.forward(100) shows exactly where forward comes from.
- list[0]
- The first item; the last item of a five-item list is list[4], not list[5].
- append, insert, remove, pop
- append adds to the end, insert puts an item at a chosen index, remove drops an item by value, pop removes the last item and hands it back.
- len, [start:stop]
- len tells you how many items a list holds; slicing pulls out a run of items, and the stop index is not included.
Do this
- Solve the smallest problem first, give it a name, then build the bigger job out of the smaller ones.
- Give each function a short docstring in triple quotes that says what it does.
- To get a value out of a function, pass it in as an argument or hand it back with return, rather than relying on shared names.
- Keep related functions together in their own file with clear names, and import them the same way you import turtle.
- To visit every item in order, loop over the list directly; you do not need indexes for this.
Watch out
- Asking for an index that does not exist stops the program with an error; the last item of a five-item list is list[4].
- Reading a local variable outside its function fails, because outside the function that name does not exist.
- from turtle import * makes names appear out of nowhere, which gets confusing once your program uses more than one library.
Found something unclear, outdated or improvable? Suggest an improvement