PYTHON FUNCTIONS

Hi all, from this text I’m going to talk about functions in Python. In python there are two types of functions,

  1. Built-in functions
  2. User defined functions

So far from the previous posts we have talked about built-in functions such as ‘print()‘, ‘len()‘. But from this post I’m going to talk about User defined functions in Python. Here I have shown the syntax of a function,

def <function_name>():

<actions>

return

Let’s see with some examples,

  • I have created my first function in Python.

1

2.png

  • But no output, because we didn’t call the function. By giving it’s name you can call the function to execute.

3

4

  • You have to define the function before you are going to call it.

5

6

  • Also we can pass arguments to a function.

7

8

  • Let’s see how to pass more than one argument.

9

10

  • Also we can use the ‘return‘ statement to get an output from a function.

11

12

  • One thing to remember is that the order of arguments matters.

13

14

15

16

  • But there is a solution in Python as well. You can use Keyword Arguments as a solution.

17

18

  • When we call the function with not matching number of arguments, then it will produce an error.

19

20

  • Python have a solution for this too. We can use Default Arguments in this scenario. Then it will use the default argument for the missing argument.

 21

22

  • But the argument what you supply has the higher precedence than the default argument.

23

24

  • There is another special type of argument as Variable Length Arguments. When we want to execute the same function with different number of arguments, then we can use variable arguments as below.

Without extra arguments :

25

26

With one extra argument :

2928

It can take any number of extra arguments :

27

30

  • Also we can create anonymous functions as well. Anonymous functions do not have the ‘def‘ keyword. It have the ‘lambda‘ instead.

31

32

That’s all about functions and passing arguments for function in Python. Hope you have cleared everything here. Hope to see you soon with another interesting topic. Thank You!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s