Part 3: Python Programming
10. Functions
Functions
As programs grow, repeating the same lines in many places becomes error-prone. A function is a named, reusable block of code. You define it once and call it whenever you need it, often with different inputs. Functions make programs shorter, clearer, and easier to fix.
Defining and calling a function
Use the keyword def, a name, parentheses for any inputs, and a colon. The body is indented. Call the function by writing its name followed by parentheses:
Parameters and return values
The names in the parentheses are parameters; the values you pass in when calling are arguments. The return statement sends a value back to whoever called the function, so you can use the result:
A function without a return statement automatically returns None. The difference between print and return matters: print only shows text on screen, while return gives a value your program can keep using.
Default and keyword arguments
A parameter can have a default value, used when the caller does not supply one. You may also pass arguments by name, which makes a call self-explanatory and lets you skip earlier optional values:
Scope
Variables created inside a function are local: they exist only while the function runs and cannot be seen from outside. This keeps functions independent and prevents them from accidentally interfering with each other:
Docstrings
A docstring is a string placed as the first line inside a function to describe what it does. Tools and the built-in help() function can read it, and it reminds future readers (including you) of the function's purpose:
A gentle look at *args and **kwargs
Sometimes you want a function to accept any number of arguments. Writing *args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dictionary:
You will not need these every day, but they power many flexible library functions. For now, remember the core idea: a function takes inputs, does work, and returns a result.
Functions are the main way programmers organise ideas. Practice by writing a function that takes a temperature in Celsius and returns it in Fahrenheit using the formula c * 9 / 5 + 32.