Lesson 16: Defining Functions

So far we have seen a number of built-in Python functions. To give some examples:

  • len()
  • print()
  • lower()
  • upper()
  • int()
  • list()
  • str()
  • etc.

These are nice and useful functions that are already defined in Python. They are very practical to use. You don’t need to do anything other than taking them and using them and they will do the job.

However, it’s also very useful to know how to define your own functions when need be.

Defining a function is pretty simple and straightforward in Python but there are a few points you should keep in mind. We will explain all of those clearly here in this lesson.

Function : N/A

No new function will be introduced in this lesson.

Used Where?

Coders usually have a practical mindset and don’t like to repeat similar tasks. By defining your own functions, you can automate a similar task instead of typing the whole function again and again.

After you define your function you can just call its name and execute it over and over for different applications and parameters.

Syntax do(s)

1) to define a function 

  • start with def,
  • choose a wise name for your function,
  • make parenthesis,
  • and inside your parenthesis include any parameter you might need (optional),
  • then use a colon at the end of the line,
  • in the next lines define your function, make sure they are indented (using tab key)


    For example:

    def no_adder(x):
        print(“No “, x)

Congratulations, you have defined your first function. To call it simply call your function with a parameter:

no_adder(“smoking”)

and it will print:

No smoking

Syntax don't(s)

1) Don’t confuse the use of print() function with return statement. (This will be explained in great detail in this lesson.)

2) Don’t forget to use a colon (:) at the end of your first line that starts with def

3) After your first line that starts with def, don’t forget to have and indentation

Just take a look at the function we define below, you can quickly observe some of the points we previously mentioned.

Example 1

>>> def helloworld():
>>>     print(“Hello World!”)

>>> helloworld()

“Hello World!”

Python User defined function in 5 simple steps:

 

  1. Our function defining starts with def
  2. Then an appropriate name for the function that’s not reserved for Python keywords (print, int, None, def, len, lower etc. would not be good names as they are examples to Python keywords)
  3. Then parenthesis (parameters inside optionally)
  4. Then colon (:)
  5. In the line below, indentation and our function.
After user defined function is finished, you can simply call it by its name as above: helloworld()

Example 2

Let’s define another function that divides any number by 100.

  • Percent is a risky name, it might be a keyword, so I will be creative.
  • Also I will use a parameter this time as I want to use this parameter in my function so that it can work for different values of the parameter.
  • Then I will call it for 5000 and see if it works.

>>> def per_hundred(x)
>>>     print(x/100)

>>> per_hundred(5000)

50

Perfect! Our function is working well.

Example 2

Now, let’s see what doesn’t work here first.

I want to assign the result to a variable so I can use it later.

>>> def per_hundred(x)
>>>     print(x/100)

>>> my_answer = per_hundred(5000)
>>> print (my_answer)

None

It didn’t work. The reason is simple but can be a great source of confusion for beginners. When we use the print() function, our function is programmed to just print and end without returning any result. Returning a value and printing are seemingly similar but very different things. In the next session you can learn how to properly use the return statement instead of print() function (or with the print() function as well.)

Return Statement

Unless you use return in your function it will not return any value. What does this exactly mean?

Often times, you want your function to do more than just printing on the display for the user, if you’re not using the return command your function will run and end, but it will not be equal to any value.

i.e.:

def plus_two(x):
    print(x+2)

Above function might print the value you intended to the display. but it runs and disappears. For instance:

When you try to assign it to a variable it won’t return any value.

my_result = plus_two(2)

Normally, you might expect my_result to equal 4. But it will return None object due to lack of return statement.

You might think, why do I need to return a value? Why can’t I just print the result and be done?

The answer to that is simple, you might not want your results to disappear and you might to assign your results to variables and use them elsewhere in your program.

For instance:

You might want to assign the same function with 3 different parameters to 3 different variables as below:

x = plus_two(2)
y = plus_two(3)
z = 
plus_two(4)

With correct use of return statement, your variables x,y,z will be assigned to 4, 5 and 6.

If you forget to use return statement in your function, or just use the print() function, your variables will be assigned to: None, None and None.

Example 3

Now, let’s see another very common mistakes while defining functions:

>>> def per_hundred(x)
>>>     return x/100
>>> my_answer = per_hundred(5000)
>>> print (my_answer)

Syntax Error: invalid syntax

As the first line that starts with def is missing a colon(:) in the end, compiler throws a syntax error.

Example 4

And finally a proper version of our example that works.

>>> def per_hundred(x):
>>>     return x/100
>>> my_answer = per_hundred(5000)
>>> print (my_answer)

50

  • colon is where it should be
  • second line is indented properly
  • return statement is used properly

Tips

1- Understanding print() vs return is very important.)

It’s important that you understand return statement properly to avoid future confusion. Although straightforward this new concept can be confusing to newcomers.

If you include a print() function this might trick you to believe that’s what your function returns a value, it doesn’t, it just prints and function ends. If you want your function to be equal to something after it runs and ends, you need to use return statement.

print() will only show an output to the screen but that doesn’t mean your function will equal to this output after it runs.

It will be more clear after a few examples:

>>> def plus_two(x):
                  print (x+2)

>>> a = plus_two(2)
>>> print(a)

None

As you can see above your program will return None, because you didn’t use the return statement.

Let’s see another example where function is properly defined.

Example 5

>>> def plus_two(x):
                  print (x+2)
                  return (x+2)

>>> a = plus_two(2)
>>> print(a)

4

Here we go, our function is properly defined. And when it’s tested with number 2 and assigned to the variable a, it functions properly. There are some important lessons here:

  1. You could exclude the print(x+2) line. It is only for showing and it doesn’t affect the actual function result.

  2. return is the last line in a function. You can not write another line after return as the function finalizes at the return line.

Example 6

You can also assign multiple variables to multiple function outputs in one line as below:

>>> def plus_two(x):
                  print (x+2)
                  return (x+2)

>>> a, b = plus_two(2), plus_two(6)
>>> print(a)

4, 8

Advanced Concepts (Optional)

1- While defining your function, you can specify your parameters so that they are optional

Example 7

Let’s use a negative step to create a decremental (just a fancy way of saying decreasing) range, convert it to a list and print it practically in 2 lines of code.

>>> a = range(5, -5, -3)
>>> print(list(a))

[5, 2, -1, -4]

Exercise 16

Lesson 17

Slicing

Interior with a Book by Richard Diebenkorn


Richard Diebenkorn

Interior with a Book by

Interior with a Book by Richard Diebenkorn

“Have you installed Python yet?”

Having Python setup on your computer can expedite the learning experience and help you gain the real life skills in a non-simulation environment. Installing Python can have different nuances that can be confusing for everyone. We compiled a complete tutorial about the best and most convenient Python installing practices Check it out by clicking the button below.
Sandra Files