Computer ScienceChapter 3: Programming Fundamentals (Python)
3.11 Functions in Python
A function
Explanation level
Introduction
As programs grow larger, they become harder to understand and manage. Writing all the code in one long block makes it difficult to find errors, reuse logic, and keep track of what each part does. Python solves this problem with functions — reusable blocks of code that perform a specific task.
Definition
A function is a named block of code that performs a specific task and can be called upon whenever that task is needed.
In simple words, a function is like a mini-program inside your program that does one specific job.
Main Idea
So far, as you have experienced throughout this chapter, we started from a single line of code and now can develop tens of it. Additionally, via conditions and iterations we are able to not only write it effectively but also control the flow of the program. However, as the code lengthens it is hard to keep track of the logic you have applied, especially in case of multiple algorithms coexisting.
So, the solution is to divide the code into segments through which it becomes handy to retain and understand large programs. Each segment does a separate task and can be called upon to fulfill that particular task, if required from the main program or another segment. Such segments are called functions.
Core Concept
- A function is defined using the `def` keyword.
- A function has a unique name.
- A function may take arguments (inputs).
- A function may return a result.
- A function is called to execute its code.
- Functions help divide a large program into smaller, manageable parts.
Detailed Explanation
Defining a Function
In Python, `def` is used to define a function with a unique name given to each function, followed by `():`.
Syntax: ```python def function_name(): # code to execute ```
Example — Simple Function: ```python def my_first_func(): print('This line is printed, when my_first_func() is called') ```
- `def` — keyword to define a function
- `my_first_func` — the name of the function
- `()` — parentheses for arguments (empty here)
- `:` — colon to start the function body
- The indented line is the body of the function
Calling a Function
To execute the code inside a function, you must call it by writing its name followed by parentheses.
Example — Calling the Function: ```python def myfirstfunc(): print('This line is printed, when myfirstfunc() is called')
myfirstfunc() # Call the function ```
Output: ``` This line is printed, when my_first_func() is called ```
Example — Drawing Lines
Let's consider another simple example where we want to draw a line on the screen, which is required to be done frequently and hence we define a `draw_line()` function.
Example — Draw a Horizontal Line: ```python def drawline(): print('' * 10)
draw_line() ```
Output: ``` __________ ```
- `'_' * 10` repeats the underscore character 10 times
- `draw_line()` calls the function, which prints the line
Example — Multiple Functions
However, if we want to extend it further and divide the drawing of vertical lines too, we will define another function and change the names of the functions, such that they are meaningful and easy to portray about their respective working.
Example — Draw Horizontal and Vertical Lines: ```python def drawhline(): print('' * 10)
def drawvline(): print('')
drawhline() drawvline() ```
Output: ``` __________ _ ```
Example — Drawing a Box
As a next step, let's adjust the number of vertical lines to be two, such that one is at the start and the other at the end of the horizontal line, and place them just under the horizontal line. Since the functionality of the function changed, so we may change the name of the functions as well.
Example — Draw a Box: ```python def drawhline(): print('_' * 10)
def drawvparallel_line(): print('|', ' ', '*26', '|')
drawhline() drawvparallelline() drawvparallelline() drawvparallelline() drawvparallelline() drawhline() ```
Output: ``` __________ | | | | | | | | __________ ```
- `draw_h_line()` draws a horizontal line
- `draw_v_parallel_line()` draws two vertical lines with spaces in between
- The function is called 4 times to create the sides of the box
- Finally, another horizontal line closes the box
Benefits of Using Functions
- Reusability: The `draw_v_parallel_line()` function is called 4 times, but the code is defined only once.
- Readability: The main program is short and easy to understand.
- Maintainability: If you need to change the line pattern, you change it in one place only.
- Organization: Each function does one specific task.
Did you understand this topic?
Your answer is saved with your learning record. It does not mark the topic as mastered.
Same supplied content as this Notes page (shared canonical source).