Python Functions


Python function are blocks of code which executes when we call it.

There are two types of functions in python. Non-return type functions and Return type functions.

Non-return type functions

def - keyword is used to define a function.

#defining the function def myFunction(): print ("Hello World") #calling the function myFunction()
Press Run to execute.

We can define parameters in a function and call it with passing arguments.

In this case we have used two arguments.

Sructure

def name_Function(parameter1,prameter2):
 Body
name_Function(argument1,argument2)

An example,

def findTotal(num1,num2): total = num1 + num2 print(total) findTotal(10,20)
Press Run to execute.

In the above example we pass the values 10 and 20 (arguments) to the num1 and num2 (parameters) and calculate the total.


When you define a certain number of parameters there should equalent number of arguments (not more or less) when calling the function.

Below code will throw an error since we use only one argument to call the function even though we define two parameters.

def findTotal(num1,num2): total = num1 + num2 print(total) findTotal(10)
Press Run to execute.


Return type functions

return - keyword is used to return a value.

When you define a return type function the output of the function will be assigned to the calling function.

Therefore we can fetch that value using a varaiable and print it.

#defining the function def myFunction(num): return num * 10 #calling the function output = myFunction(5) print (output)
Press Run to execute.
Any line of code after the return statement will not get executed.

The below code is will calculate the area, and also you can identify that print("bye") statement won't get executed.

def findArea(width,height): area = width * height return area print("bye") print("The area is :", findArea(8,5)) print("The area is :", findArea(5,10))
Press Run to execute.


Another topic to focus on is default arguments.

Default Arguments

When we define default arguments, even though we doesn't pass arguments to those parameters it will execute.
def word(first , last="flix"): word = first + last return (word) print (word("net" , "working")) print (word("net"))
Press Run to execute.





Concept & Design by Code94 Labs