Python Basics

Python Functions

So far we have seen using python created function for various purpose such as to know the length of list, sort list elements, print information etc.

Can we create our own function?

Yes. We can create our function in Python.

Syntax

def function_name():

//required code to accomplish a task

  1. User defined function should always begin with the keyword def
  2. Immediate after def keyword we need to write the function name
  3. We can use any function name and it should not contain space or special characters.
  4. Corresponding code of blocks must follow indent (min. one space)

Example:

Lets create a function that prints a message

def PrintMessage():

print(“Hello Friends”)

How can we call the above function?

Where ever I want to print the message in my python script, all I have to do is call the function.

PrintMessage()

Output: Hello Friends.

Why do we need to create a function?

In python programming, we may land in a situation where a code of block is repeatedly required to write to get a desired result.

Example

Lets say, I am working on GST sales tax calculation application and in the python script there are price of 100 products and in the code I need to calculate GST tax added price for all the products. Suppose there is 18% sales tax is on every product.

Then in the python script, I need to write code that will calculate 18% of the product price and then that is into the actual price. So for 100 products I need to write 100 times the same code whose main task is to calculate tax and prepare the sales price(Actual price+sales tax).

All I can do to avoid such time consuming and effort consuming approach, is to create a function which accepts price, and prints sales price.

Example

def CalculateSalesPrice(ActualPrice):

SalePrice=ActualPrice+ActualPrice*18%

print(SalePrice)

CalculateSalesPrice(12000)

CalculateSalesPrice(8000)

CalculateSalesPrice(10000)

CalculateSalesPrice(2000)

CalculateSalesPrice(4000)

Output

13160

9440

11800

2360

4720

See in the above, I have create a function which accepts value, calculates and prints the sales price. The desired value which is passed in the parenthesis is known as “Argument”. We can accept more than one argument in a function and we must have to define in the function itself.

In the above example, the function which I have defined takes one argument. And If I supply more than one argument while calling it, then it will throw error. Similarly, if I do not supply any argument then also it will throw error.

Lets take another example.

Create a function that calculates addition value of supplied two values.

Solution

def AdditionCalculator(num1,num2):

result=num1+num2

print(result)

AdditionCalculator(100,200)

AdditionCalculator(200,300)

AdditionCalculator(300,400)

AdditionCalculator(-100,-200)

Output:

300

500

700

-300

Note: In python we can pass list, tuple, string, float or any data type as an argument.