Python Functions

python-functions-ipcisco-1

A Python Function is a python code that is defined previously to do a specific job. And whenever we call this Python Function, it runs and returns with the result of the function.

 

We can define a function in python with “def” keyword. After this keyword, we write the name of the function that we will create. And we use round paranthesis after this name. We can use any parameter fort his function ot not. If we use a parameter we can define it inside these paranthesis. If we use one more parameter with this function, then we define each parameter inside these paranthesis with a comma (,) between them.

 


You can also check Python Lambda Function


 

 

When we call the functions, we need to give these parameters. If we give missing parameter then it will give an error. So, we need to use the same number of parameters both for definition and calling.

 

Normally we need to define the parameters in order. But with key:value syntax, we can give these parameters out of order.

 

We use colon (:) operator at the end of this definition. After colon (:) operator at the end of this statements, we can write the body of this function. In this body the jobs that will be done by this function, is mentioned.

 

Here one important thing is, while we define a function, we use colon (:). But when we call this function, we do not use colon (:) at the end of the function.

 

We can define our own functions with this method. Instead of writing the same thing times and times, we can define one time and then we can use call function whenever we need the same job.

 


You can also check Python While Loop


 

A basic Python function can be created like below:

 

def first_function():
  print("Let’s create a Python Function!")

 

When we write this code, we do not get any response as an output. Because this is a function definition. But whenever we call this Python function in a code, then it returns with the output of this function. Let’s call this function with the below code.

 

def first_function():
  print("We are learning Python Functions!")
 first_function()

 

The output of this python code will be:

 

We are learning Python Functions!

 

We can also add arguments to use in the functions inside paranthesis. So, now let’s define some functions with Lord of the Rings Characters and learn how it works. Here, we will define three functions and each function will add a different string and combine it with the variable that we call the function with.

 

def elves(x):
  print(x + " is an Elf.")
def dwarves(x):
  print(x + " is a Dwarf.")
def human(x):

  print(x + " is an Human.")

elves("Legolas")
elves("Elrond")
elves("Arwen")
dwarves("Gimli")
human("Aragorn")

 

The output of this code will be:

 

Legolas is an Elf.
Elrond is an Elf.
Arwen is an Elf.
Gimli is a Dwarf.
Aragorn is an Human.

 

Now, let’s define a function for a math calculation. In this function, we will use two parameters. And the output of this function will be the multiplication of these parameters.

 

def our_function(x,y):
               print(x * y)

our_function(3,10)
our_function(5,11)

 

The output of this function will be like below:

 

30
55

 

python-functions-ipcisco-1

 

Let’s show another example for Python functions.

 

def data(name,surname,no):
 print("Name:", name, "Surname:",surname,"No:",no)

data("Gokhan","Kosem",1234)

 

Name: Gokhan Surname: Kosem No: 1234

 

 


 

Default Value in Functions

 

As we have mentioned before, we give the parameters to the functions during the definition of a function. This is called default value of this function. If we give a default value as a parameter value in this function, whenever we call this function without any parameter, function uses this default value.

 

def newfunc(name = "Legolas"):
  print(name + " is an Elf." )

 newfunc("Elrond")
newfunc("Galadriel")
newfunc()

 

As an output, we will receive,

 

Elrond is an Elf.
Galadriel is an Elf.
Legolas is an Elf.

 

python-functions-ipcisco-2

 

As you can see above, if we do not give any parameter, the function will use its default value, “Legolas”.

 

Let’s do another example to understand this default value better.

 

def data(name="No data" ,surname="No data", no="No data"):
 print("Name:", name, "Surname:",surname,"No:",no)

data(name="Gokhan")

 

Name: Gokhan Surname: No data No: No data

 

 


 

Using Asterisk (*) With Python Functions

 

We use asterisk (*) with python function when we do not know the arguments that we will use during function call. Here, we use asterisk (*) sign before the parameter of the function.

 

With the help of this sign, out function can receive a tuple of arguments.

 

def new_func(*elves):
  print("The strongest Elf is {} " + elves[1])
new_func("Elrond", "Galadriel", "Legolas")

 

The output of this python code will be:

 

The strongest Elf is {} Galadriel

 

 Let’s do another example to understand this usage better.

 

def multipfunc(*a):
    result=1
    for i in a:
               result=result * i
    print(result)
multipfunc(3,6,10)

 

The result of this code will be :

 

180

 

python-functions-ipcisco-3

 

Another example is like belowi. Here, we will add the given numbers with the function.We can use any numbers with this fucntion.

 

def letsadd(*args):
    return sum(args)
print(letsadd(15,25,50))

 

90

 


 

The Return Statement

 

With return statement, we can define the return value of a statement. This can be a fixed number, a result of a calculation or anything else.

 

Below, a result of a calculation will be used as return value. We will get a square of the given number as a return.

 

def newfunction(a):
  return a * a
print(newfunction(5))

 

The output will be:

 

25

 

In another example, we will check the number is greater that 0 or not. According to it, we will get a return.

 

def newfunction(a):
    if a > 0:
        return "Positive"
    elif a <0:
        return "Negative"
    else:
        return "Zero"
 print(newfunction(-2))

 

The output of this python code will be:

 

Negative

 

how-to-create-python-function-ipcisco

 


 

The Pass Statement

 

The pass statement is used to get no error if we use an empty function. You can use this empty function for variety of reasons in python programming. If you would like to avoid errors, you should use at least pass statement inside this function.

 

def newfunc():
  pass

 


 

Python Recursive Functions

We can call any other function in Python function. What if we call the function itself in this function? In Python, this is called recursive functions. With these functions, we can call the function inside it again. With the help of this code, we can do more effective jobs in Python. But we should be careful while using recursion with functions. Because, if we use this code wrongly, we can go into a loop and an endless process begins. This can consume the system resources.

 

Below, there is a basic function that calculates factorial of a given number.

 

def findfactorial(a):
    if a == 1:
        return 1
    else:
        return (a * findfactorial(a-1))
print(findfactorial(5))

 

The output will be:

 

120

 

python-recursive-functions-ipcisco

 

In this lesson, we have learned Python Function details. We have seen how to create a function in python. How to call this function. You will use Python functions too much in your codes. So, to learn more on fucntions, you should do more practice on them.

 

Back to: Python Programming Course > Python Functions

Leave a Reply

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

Python Programming Course

Collapse
Expand
Latest Blog Posts