Functions in Python

Functions are an important part of a programming language. It is used in all of the programming languages. Try writing a program which calculates areas of 100 different circles each of them have different radii. It would not be that hard to write this program but you might just have to copy and paste the same code 100 times, which is not the best practice. For solving this problem the concept of functions was introduced. Once you write a code in function, you don’t need to write the code more times, you can just call the function.

  1. Defining a function

Defining a function is really easy in python. You just use the ‘def’ keyword built in python and give a space and write the name of the function, you can name the function anything you want. And put open and close parenthesis(small brackets) and write a colon to start a function. After that go in another line and give four space spacing and start writing the function.

If you run this program there will be no output because we haven’t called the function yet.

  1. Calling a function

Calling a function is also really easy. You just need to write the name of the function and write open and close parentheses.

Outpt:

You can call the function as many times as possible.

For example:

Output:

  1. Returning a function

Returning a function means to give a value to the function declared. For example if you call a function with setting it with a variable and print it, it would print None.

Output:

Why is it? It is because the function does not have any value, returning a function simply means giving a value to the function.

We can return a value by just using the ‘return’ keyword. 

Output:

  1. Passing Variables with functions

We learned that with the help of function, we can do some steps as many times as possible without writing it multiple times. But in many cases, we have to do the same thing but with different values. For doing that, we can pass variables. It is really easy to pass variables to  function. You just need to declare the variable inside the parentheses of the functions. And pass the value of the variable while calling the function.

Output:

You can do this as many times as possible with different value.

Output:

2 Comments on “Functions in Python”

  1. Wonderful, best documentation of python functions I ever read. I read others in module 1 as well but this is by far the best and most understandable

Leave a Reply

Your email address will not be published. Required fields are marked *