Working With Functions
Working With Functions
def my_function():
print("Hello from a function")
def my_function():
print("Hello from a function")
def calcSomething(x):
r=2*x**2
return r
def calcSomething(x):
r=2*x**2
where return r
• def means a function definition is starting
• identifier following 'def' is the name of the function, i.e., here the function name is
calcSomething
• The variables/identifiers inside the parentheses are the arguments or parameters
(values given to function), i.e., here x is the argument to function calcSomething.
• There is a colon at the end of def line, meaning it requires a block
• The statements indented below the function, (ie., block below def line) define the
functionality (working) of the function. This block is also called body-of-the-function.
Here, there are two statements in the body of function calcSomething.
• The return statement returns the computed result.
Note: The non-indented statements that are below the function definition are not part
of the function calcSomething's definition.
def calcSomething(x):
r=2*x**2
return r
a=int(input("Enter a number:"))
print(calcSomething(a))
The most important reason to use functions is to make program handling
easier as only a small part of the program is dealt with at a time, thereby
avoiding ambiguity. Another reason to use functions is to reduce program
size. Functions make a program more readable and under- standable to a
programmer thereby making program management much easier.
A Python function is a block of organized, reusable code that is used to
perform a single, related action. Functions provide better modularity
for your application and a high degree of code reusing.