Functions in Python

In the previous article, we saw how we could optimize code for two different problems. There is another way in which we can increase the effectiveness of code, that is true the use of in-built functions or user-defined rather than the use and repeat of long lines of code. So in this article, we will be looking at the Functions in Python. Let us first look at an example, imagine that you are working in a huge company that is writing a huge application. The company application relies on the use of dates a lot such as date of publishing, date of signing etc.

The company needs to utilize a standard format for printing the dates such as dd-mm-yyyy. The best way to fill this application programming requirement would be through the use of a date function.

Syntax and Usage of Functions in Python

We use the def keyword to define a new function, followed by the function name:

def functionname( ):
    Function Statements
print("Output Statement")
functionname( )

Let us look at a function example:

def fun():
	print("fun() called")
print("Before calling fun()")
fun()
print('After calling fun()')
Output:
Before calling fun()
fun() called
After calling fun()

The output statement of “Before calling fun()” lies outside of the function(as shown by the indentation block), we see that the function is then referred to by name and then prints out executes the statement which is defined within the function.

We can also provide input to the functions at the time of execution of the program.

def printDate(d,m,y):
    print(d,m,y,sep="- ")

print("India  became independent on")
printDate("15,""08","1947")
Output:
India  became independent on
15- 08- 1947

The program accepts the input of three different parameter variables and then converts the input to the expected format to print the output.

def getDate(d,m,y):
    print d + "-" + m + "-" + y

print("India  became independent on")
printDate("15,""08","1947")

Now, look at the program code below and try to guess the resultant output.

def greet_msg( ):
    print("Hi")
    print("Welcome to CodeKyro")
def exit_msg( ):
    print("Please visit again.")
    print("Bye")
greet_msg( )
print("Hope you are enjoying")
exit_msg( )

There are two functions in the code above, and we can see when the function is executed or called(its name is mentioned outside of the definition). First the greet_msg( ) function and then followed by a print statement and then a final exit_msg( ) function call.

Output:
Hi
Welcome to CodeKyro
Hope you are enjoying
Please visit again.
Bye

Hence we have revised the Python functions concept, now we will take a look at the Applications of Functions in Python.

Leave a Comment