Introduction to Functions
Just like a value can be associated with a name, a piece of logic can be given
a name by defining a function. In Python, functions are defined using the
Python uses indentation to identify the block of code that is part of the function. Usually 4 spaces are used as indentation.
It may look like forcing indentation is a big constraint in the beginning, but you'll not even notice it as you get used to it. In fact, every good programmer indents his code any way.
Python has a great feature called docstrings. Docstring is a string literal that occurs as the first statement in a function, used to describe the function. In Python, it is a common practice to put some examples in the docstring demonstrating how that function behaves. The following example adds a docstring with examples to the square function.
In most examples and exercises, PythonMonk tries to run the examples specified in the docstring as testcases to verify the correctness of the function.
Time for an exercise. Try to implement a function
cube that takes a number as argument and returns
Once a function is defined, it can be used in other expressions or in defining new functions. The following example demonstrates the case of using already defined square function to define a new function.
Now, it is your turn. Implement a function
sum_of_squares that takes 2
numbers as arguments and returns sum of its squares. You should call the square
function to compute square.