In the part 2 we've shown most basic ways of definining functions in Python.
Let's elaborate on that a bit more, using some examples.
First, a simple function just doing something, for instance printing text to screen (something tradinionally called a procedure rather than a function), is defined like this:
... and called like this:
So execution of the program below:
...results in the following output:
What if we want to return value from function, so we can use it in the moment it's called? Well, let's simply use return keyword:
The type doesn't have to be defined.
As an example we'll assign the value returned by the function above to pi variable, and then print it to the screen.
Result:
What if we want our function to take some parameters?
This is when the things became interesting, as Python allows us to defined both named and unnamed (positional) paramaters. By default, both. So we can define our function as:
...and call it in two ways:
Or:
...both resulting in:
Please note that if we call our function with named parameters, their order doesn't matter. So call:
...also results in:
The last thing for today will be default parameter value, which is defined using the = sign.
An example looks like this...
( ** is power operator, a**b means a to the power of b).
The above function has two parameters, but the second one (exponent) has default value. This means that if we skip the second param, our function becomes simply square function.
So the "full-param" call looks like this:
...and results in:
And the call using default parameter value can look like this:
..resulting in:
There are more details about defining and calling functions in Python, which we can elaborate further on in future, but I think for now we've covered the most important features.
No comments:
Post a Comment