Python Functions – Concept
A Function is a code segment or sub-program separately defined with some identification for future access.
Advantages of Functions
- Reusability – A function can be used multiple times.
- Modularity – A large program can be divided into smaller modules.
- Readability Enhancement – Functions make programs easier to understand.
Two Forms of Function
- Definition
- Invocation or Calling
Function Definition
Definition specifies the code to be executed when the function is invoked. It describes the job of the function.
Function Invocation
Invocation means requesting the function to start executing the code written in its definition.
Relationship Between Definition and Invocation
- No function can be invoked unless it is defined.
- A well-defined function cannot execute unless it is invoked.
The __main__ Block
__main__ represents the main execution context of a Python program.
We can check the current module name using the predefined variable
__name__.
Example:
print(__name__)
Caller and Called Function
- Caller: The function or program section that calls another function.
- Called Function: The function which is called by another function.
Example Program
# Definition of function test
def test():
print("Hi from test")
# Main program
print("Starting of main")
test() # Invocation of test function
print("The End")
Types of Functions in Python
- Pre-defined / Built-in / Library Functions
- User-defined Functions
How to Define a User-defined Function?
A function definition contains two main parts:
- Header – Contains the identification of the function.
- Body – Contains the executable statements of the function.
Parts of Function Header
defkeyword- Name of the function
- Parameters or arguments, if any
General Syntax
def function_name(parameters):
statements
Return Value
A return value is a value sent back by a function to the caller after completing its job.
A function may be defined either to return a value or not explicitly return a value.
The return keyword is used to return a value from a function.
When return is executed, the function immediately ends.
Forms of Return Statement
return
return val
return var
return expression
Important Note
It is common to place the return statement at the end of the
function when the function has completed its required work. However,
return does not have to be physically the last statement.
Once executed, it immediately terminates the function.
Function Not Returning a Value
def NoRet():
print("I am not returning any")
return
Function Returning a Value
def RetVal():
return 5
Function Returning a Variable
def RetVar():
num = 10
return num
Function Returning an Expression Result
def RetExp():
return 5 + 2
Complete Example
# Function not returning a value
def NoRet():
print("I am not returning any")
return
# Function returning a value
def RetVal():
return 5
# Function returning a variable
def RetVar():
num = 10
return num
# Function returning expression result
def RetExp():
return 5 + 2
# Main program
NoRet()
RetVal()
res = RetVar()
print("res =", res)
res = RetExp()
print("res =", res)
Practice Questions
-
Write a Python function
getStr()that returns the string"Hello, Python!"and print the returned value from the caller. -
Write a function named
getNumber()that returns the integer42. Call the function and store the result in a variable, then print the variable. -
Write a function
is_even()that returnsTrueif a hardcoded number inside the function is even; otherwise returnFalse. Print the function's return value using its caller. -
Write a Python function
return_none()that does not explicitly return any value. Call the function and print its return value to verify its return type. -
Write a function
pi_value()that returns the mathematical value of Pi as3.14159. Call the function, store the result in a variable, and print it. -
Write a function
get_person()that returns two values: a hardcoded name (string) and an age (integer). Store the returned values in separate variables and print them. -
Write a function
get_marks()that returns three hardcoded marks (integers). Call the function and store the values in a tuple. Print the tuple. -
Write a function
get_status()that returnsTrueand"Success"as a tuple. Unpack the returned values and print them separately. -
Write a function
is_positive()that returns"Positive"if a hardcoded number is greater than zero,"Negative"if less than zero, and"Zero"otherwise. Print the return value. -
Write a function
is_vowel()that returnsTrueif a hardcoded character is a vowel andFalseotherwise. Call the function and print the result. -
Write a function
square()that returns the square of a hardcoded number. Print the function's return value. -
Write a function
calculate_area()that returns the area of a rectangle with hardcoded width and height values. Print the returned area. -
Write a function
convert_to_fahrenheit()that returns the Fahrenheit equivalent of a hardcoded Celsius temperature. Print the function's return value. -
Write a function
count_down()that prints numbers from 5 to 1 using a loop and then returns"Done!". Print the function's return value. -
Write a function
sum_first_n_numbers()that returns the sum of the first 10 natural numbers. Call the function and print the result. -
Write a function
outer_function()that returns another functioninner_function(). Callouter_function()and execute the returned function. -
Write a function
get_multiplier()that returns a function that multiplies a given number by 3. Callget_multiplier(), store the returned function in a variable, and use it to multiply 5. Print the result.
def → Defines the functionfunction_name() → Invokes / calls the functionreturn → Sends a value back to the caller