When the same steps are needed in many places, they are written once as a function. A function has a name, takes inputs and gives back a result, which keeps programs short and easy to test.
Built-in Functions
Python provides many ready-made functions. Examples are print(), len(), type(), abs(), max(), min(), sum(), round(), sorted() and range(). The math module adds functions such as sqrt() and pow() when imported.
Defining and Calling a Function
A function is defined with the keyword def, a name, a list of parameters in brackets and a colon. The indented body follows. The return statement sends a value back to the caller, and a function without return gives None. A function is used by writing its name with arguments, such as area(4, 5). The values in the definition are parameters, and the values given in the call are arguments.
Definition: Function. A named block of code that performs a task, may accept parameters and may return a value.
Default and Keyword Parameters
A parameter can be given a default value, which is used when the caller does not supply that argument, as in def power(x, n=2). Parameters with defaults must come after those without. In a call, arguments can be passed by position or by keyword, such as power(n=3, x=2), and keyword arguments can be given in any order. Python also allows a variable number of arguments using *args, which collects them in a tuple.
Command Line Arguments
A program can receive values when it is started. They are stored in the list sys.argv, where sys.argv[0] is the name of the script and the rest are the arguments, all as strings. For example, running python add.py 4 5 gives sys.argv equal to ["add.py", "4", "5"].
Good functions do one job and have a clear name. A short comment or docstring, a string placed on the first line of the body, explains what the function does, and help(function_name) displays it. A function can return more than one value by returning a tuple, as in return a + b, a - b, which the caller can unpack into two variables. Functions can call other functions, and a function can even call itself, which is called recursion. Breaking a large program into small functions makes it easier to write, test and reuse.
Table 2.3: Parameters and arguments
| Kind | Example | Remark |
|---|---|---|
| Positional | area(4, 5) | Order matters |
| Keyword | area(b=5, l=4) | Order free |
| Default | def f(x, n=2) | Optional argument |
| Variable | def f(*args) | Many arguments in a tuple |
Example 2.3: A function with a default parameter
Problem: Write a function power(x, n=2) that returns x raised to n, and show calls with and without n.
Solution:
- Define the function with n defaulting to 2.
- Call it with one argument, with two, and with keywords.
Result: power(5) gives 25, power(2, 3) gives 8 and power(n=4, x=2) gives 16.
def power(x, n=2):
return x ** n
print(power(5), power(2, 3), power(n=4, x=2))
def total(*nums):
return sum(nums)
print(total(1, 2, 3, 4))
print(abs(-7), max(3, 9, 4), round(3.14159, 2))
Output
25 8 16
10
7 9 3.14
Common mistakes
- Putting a parameter with a default before one without.
- Forgetting return, so the function gives None.
- Confusing printing a value with returning it.
Key takeaways
- A function is defined with def and gives a value with return.
- Parameters appear in the definition and arguments in the call.
- Default values must come last.
- sys.argv holds command line arguments as strings.
Practice questions
- What does a function without a return statement give?
- What is a default parameter?
- What is sys.argv[0]?
Answers to the practice questions
- None.
- A parameter with a value that is used when the caller gives no argument.
- The name of the script.
Sources
- Official BCA syllabus Python Programming, course code 26BCA403SEC01, Unit II
