20 - Functions in Python

🧢 Tags:: #Python_Basics
Up:: 21 - Function Arguments
Down:: 19 - Break and Continue
πŸ—ƒ Resources:: Playlist
2023-12-20 - 12:00

A function is a block of code that performs a specific task whenever it is called. In bigger programs, where we have large amounts of code, it is advisable to create or use existing functions that make the program flow organized and neat.

There are two types of functions:

  1. Built-in functions
  2. User-defined functions

Built-in functions:

These functions are defined and pre-coded in python. Some examples of built-in functions are as follows:
min(), max(), len(), sum(), type(), range(), dict(), list(), tuple(), set(), print(), etc.

User-defined functions:

We can create functions to perform specific tasks as per our needs. Such functions are called user-defined functions.


def function_name(parameters):
	# Code and Statements

Calling a function:

We call a function by giving the function name, followed by parameters (if any) in the parenthesis.


def name(fname, lname):
	print("Hello,", fname, lname)
name("Sam", "Wilson")


Hello, Sam Wilson

Main Example

def calculateGmean(a, b):
  mean = (a*b)/(a+b)

def isGreater(a, b):
    print("First number is greater")
    print("Second number is greater or equal")

def isLesser(a, b):

a = 9
b = 8
isGreater(a, b)
calculateGmean(a, b)
# gmean1 = (a*b)/(a+b)
# print(gmean1)
c = 8
d = 74
isGreater(c, d)
calculateGmean(c, d)
# gmean2 = (c*d)/(c+d)
# print(gmean2)