Step 1 of 8 · Reading · ~3 min
Learn
Functions
Defining Functions
You will write your own functions, return several values from one, split a stdin script into functions behind a __main__ guard, and write a recursive function that stops.
You have called functions since your first program (print, len, sorted), with keyword arguments such as end= and start=. Now you write them.
def, parameters, return
price and percent are parameters: names listed in the def line. 80 and 25 are arguments: the values supplied by a call. A call binds arguments to parameters, runs the body, and evaluates to what return sent back. percent=10 is a default value, used when the caller omits it; keep defaults to numbers, strings or None, placed after parameters without one. The string on the first line of the body is a docstring; help(discounted) shows it. The full binding rules are the next lesson.
return sets the value of the call and ends the call at once; lines after it never run.
return versus print
A function with no return gives back None. print shows a value; return hands it to the caller.
Returning several values
As in Tuples and Unpacking, a comma after return builds a tuple the caller unpacks.
Without unpacking you hold one tuple; the names must match the count returned.
Local variables
Parameters and names assigned in the body exist only while that call runs; each call starts fresh.
Functions calling functions
A body can call your other functions like len:
Recursion
A function may call itself. It needs a base case, an input answered without another call, and every other input must move toward it.
Without the if, at a depth of 1000 (sys.getrecursionlimit()) Python raises RecursionError: maximum recursion depth exceeded. So does countdown(5000), base case or not. If the depth could be large, write a loop.
Scripts: main() and the guard
Functions do the work; main() does the reading and printing:
Python sets __name__ to "__main__" in the file you run and to the module's name when another file imports it, so an import does not run main().
Common mistakes
- Not unpacking:
g = pair_stats(x)stores a tuple, soprint(f"gcd={g}")showsgcd=(6, 3)instead ofgcd=6. /for whole numbers:12 / 4is3.0, so it prints36.0, and a huge result prints like9.99999866000004e+17. Use//.- Miscounting: stop one operation early or late and
a == breports the wrong count. Trace an input where the loop runs once. - Printing instead of returning in a helper: the caller gets
Noneand the helper's line appears out of place.
Your exercise
Write euclid(a, b) returning two values, and lcm(a, b) that calls euclid, then fill in the loop body in main(). The starter supplies the guard. The likeliest slip is the step count, so check a == b by hand.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…