3. Control Flow: Functions
Function Fundamentals
As your code grows larger and more complex, it becomes important to modularise your code by breaking it up into functions. This abstraction of functionality is often desired for repetitive tasks and easy maintenance.
FunctionIn programming, a function is a sequence of expressions that performs one or multiple related tasks, packed in a single callable unit.
Functions are defined using the #\color{#8959A8}{\mathtt{\text{def}}}# keyword. We have already seen the syntax for defining functions on multiple occasions, but it was always provided. We have also seen multiple examples of function usage, with built-in functions like #\mathtt{\color{#4271ae}{\text{len}}\text{()}}# and #\mathtt{\color{#4271ae}{\text{range}}\text{()}}#.
#\begin{split}
\color{#8959A8} {\mathtt{def}} \textit{ } & \textit{name}([\textit{parameter}_\textit{1}\mathtt{\text{,}}\textit{parameter}_\textit{2}\mathtt{\text{,}}\dots])\mathtt{:}\\
& \textit{statement}\\
[ & \color{#8959A8} {\mathtt{return}} \textit{ value}_\textit{1}\mathtt{\text{,}}\textit{ value}_\textit{2}\mathtt{\text{,}}\dots]
\end{split}#
Here name is the designated name for the function, it's the reference that will be used in succeeding code.
A function can have a variable amount of parameters, ranging from zero to a lot. Similar to loops, these parameters are to be used in the subsequent code block contained by the function.
The main routine of the function is defined in the indented statement, the statement can be any valid program and can thus contain conditional constructs, loops, or even other function definitions.
Optionally, a function can return a number of values. If the function contains a #\color{#8959A8} {\mathtt{\text{return}}}# statement, it results in the value(s) when evaluated. If not, the function returns #\color{#F5871F} {\mathtt{\text{None}}}# instead.
For example, here we see the function definition of #\mathtt{\text{summation()}}#. The function #\mathtt{\text{summation()}}# has #\mathtt{\text{summation}}# as name. The function has two parameters, #\mathtt{\text{x}}# and #\mathtt{\text{y}}#. The function includes one statement, the variable assignment for #\mathtt{\text{val}}#. The function returns the value of #\mathtt{\text{val}}#, which is equal to #\mathtt{\text{x}\color{#3e999f}{\text{ + }}\text{y}}#. |
|
Or visit omptest.org if jou are taking an OMPT exam.