Thursday 22 July 2021

Python crash course part 7: more on defining functions

 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:

def just_do_it():
    print("Just do it")

... and called like this:

    just_do_it()

So execution of the program below:

# !/usr/bin/python3

def just_do_it():
    print("Just do it")

def main():

    just_do_it()

...results in the following output:

Just do it

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:

def please_return_something():
    return 3.14

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.

def main():

    pi = please_return_something()
    print(pi)

Result:

3.14

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:

def divide(nominatordenominator):
    return nominator/denominator

...and call it in two ways:

    print(divide(6,2))

Or:

    print(divide(nominator=6,denominator=2))

...both resulting in:

3.0

Please note that if we call our function with named parameters, their order doesn't matter. So call:

    print(divide(denominator=2,nominator=6))

...also results in:

3.0

The last thing for today will be default parameter value, which is defined using the = sign.

An example looks like this...

def power(ab = 2):
    return a**b

( ** 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:

    print(power(2,3))

...and results in:

8

And the call using default parameter value can look like this:

print(power(3))

..resulting in:

9

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

Python crash course part 10: inheritance and polymorphism

In the last part we've shown how to create and use a class in Python. Today we're going to talk about inheritance: wchich means cre...