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.

  • script.py
1
2
3
4
5
6
#defining the function
def myFunction():
print ("Hello World")
#calling the function
myFunction()
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  • IPython Shell
In [1]:
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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,

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.



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.

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.



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.





Concept & Design by Code94 Labs