Functions in python provide organised, reusable and modular code to perform a set of specific actions. Functions simplify the coding process, prevent redundant logic, and make the code easier to follow. This tutorial describes the declaration and utilization of functions in Python.
Python has many built-in functions like print(), input(), len(). Besides built-ins you can also create your own functions to do more specific jobs – these are known as user-defined functions.
Defining and calling Functions
Using the def statement is the most common way to define a function in python. This statement is a so called clause compound statement with the following syntax:
def functionName(parameters): statement(s)
functionName is known as the identifier of the function. Since a function definition is an executable statement its execution binds the function name to the function object which can be called later on using identifier.
statement(s) -also known as function body, are nonempty sequence of statements executed each time the function is called.
Here is an example of a simple function whose purpose is to add two numbers every time when it’s called:
# defining function as add_two and giving x and y as parameters def add_two(x, y): print(x+y) # body assigned to add x and y add_two(2, 4) # calling the function # output 6
Now lets make a function to divide two numbers:
# defining function as divide and giving dividend and divisor as parameters def divide(dividend, divisor): print(dividend/divisor) # body assigned to divide dividend and divisor divide(20, 5) # calling the function #Output 4.0
Now lets define a function as multiply with 4 parameters:
def multiply(a, b, c, d): print(a*b*c*d) multiply(4,7,9,6) #Output 1512
Now lets define a function to print greatest number:
def greatest(x,y,z): if (x>y)and(x>z): print(x,"is greatest") elif (y>x)and (y>z): print(y,"is greatest") else: print(z,"is greatest") greatest(43, 78, 5) #Output 78 is greatest
Thanks for give usefull knowledge .
thanks keep visiting us
Thanks for this
thanks keep visiting us