Skip to content

Python Functions – Concept

A Function is a code segment or sub-program separately defined with some identification for future access.

Advantages of Functions

  1. Reusability – A function can be used multiple times.
  2. Modularity – A large program can be divided into smaller modules.
  3. Readability Enhancement – Functions make programs easier to understand.

Two Forms of Function

  1. Definition
  2. 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

  1. No function can be invoked unless it is defined.
  2. 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

  1. Pre-defined / Built-in / Library Functions
  2. User-defined Functions

How to Define a User-defined Function?

A function definition contains two main parts:

  1. Header – Contains the identification of the function.
  2. Body – Contains the executable statements of the function.

Parts of Function Header

  1. def keyword
  2. Name of the function
  3. 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

  1. Write a Python function getStr() that returns the string "Hello, Python!" and print the returned value from the caller.
  2. Write a function named getNumber() that returns the integer 42. Call the function and store the result in a variable, then print the variable.
  3. Write a function is_even() that returns True if a hardcoded number inside the function is even; otherwise return False. Print the function's return value using its caller.
  4. 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.
  5. Write a function pi_value() that returns the mathematical value of Pi as 3.14159. Call the function, store the result in a variable, and print it.
  6. 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.
  7. Write a function get_marks() that returns three hardcoded marks (integers). Call the function and store the values in a tuple. Print the tuple.
  8. Write a function get_status() that returns True and "Success" as a tuple. Unpack the returned values and print them separately.
  9. 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.
  10. Write a function is_vowel() that returns True if a hardcoded character is a vowel and False otherwise. Call the function and print the result.
  11. Write a function square() that returns the square of a hardcoded number. Print the function's return value.
  12. Write a function calculate_area() that returns the area of a rectangle with hardcoded width and height values. Print the returned area.
  13. Write a function convert_to_fahrenheit() that returns the Fahrenheit equivalent of a hardcoded Celsius temperature. Print the function's return value.
  14. 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.
  15. Write a function sum_first_n_numbers() that returns the sum of the first 10 natural numbers. Call the function and print the result.
  16. Write a function outer_function() that returns another function inner_function(). Call outer_function() and execute the returned function.
  17. Write a function get_multiplier() that returns a function that multiplies a given number by 3. Call get_multiplier(), store the returned function in a variable, and use it to multiply 5. Print the result.
Key Point to Remember:

def → Defines the function
function_name() → Invokes / calls the function
return → Sends a value back to the caller