A function is a named block of code that performs one task. You have already used many: print(), len(), input(). This section shows how to write your own.
Why functions
Decomposition: a large problem is split into smaller, manageable parts.
Reuse: write the code once, call it many times, even from other programs (Unit 12).
Less duplication: a fix in one place fixes every use.
Readability and testing: a well-named function explains itself and can be tested on its own.
Kinds of functions
Kind
Meaning
Examples
Built-in
Always available in Python
print(), max(), len(), input()
User-defined
Written by you with def
factorial(), calculate_tax()
Anonymous (lambda)
A small unnamed function written as one expression
lambda x: x * x
Defining a function
Syntax
def function_name(parameter_1, parameter_2, ...): """Optional docstring describing the function.""" statement(s)
def starts the function definition; the name follows the identifier rules.
The parentheses hold zero or more parameters: names that receive the input values.
The header ends with a colon, and the indented lines form the function body.
A string on the first line of the body is the function’s docstring, shown by help(function_name).
Defining a function only creates it; nothing in the body runs until the function is called: function_name(argument_1, argument_2, ...). The values given in the call are arguments; each one is bound to the matching parameter.
Parameter
Argument
Where
In the function definition
In the function call
What
A name waiting for a value
The actual value passed
Example
n in def factorial(n):
5 in factorial(5)
Key takeaways
Functions break programs into reusable, testable pieces.
Python has built-in, user-defined and anonymous (lambda) functions.
def defines; a call with parentheses runs the body.
Parameters receive arguments.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Explain the difference between a function definition and a function call, with an example.
Show worked answer
A function definition creates the function: it gives the name, the parameter list and the body, as in def greet(name): print("Hello", name). Nothing is printed when this runs. A function call executes the body with actual values for the parameters, as in greet("Nav"), which prints Hello Nav. A function is defined once but can be called any number of times with different arguments.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/functions-and-file-handling-in-python/defining-and-calling-functions/ to read this page.