User-Defined Functions - 10

User Defined Functions in Python

Introduction to Functions

A function is a block of code that performs a specific task. Functions help in organizing programs into smaller and manageable parts.

Instead of writing the same code repeatedly, a function can be created once and used many times whenever required.

Why Do We Use Functions?

  • Reduce repetition of code.
  • Make programs easier to understand.
  • Make debugging easier.
  • Improve program organization.
  • Increase code reusability.

Types of Functions in Python

Functions in Python are mainly of two types:

  1. Library Functions (Built-in Functions)
  2. User Defined Functions

Library Functions

Library functions are predefined functions provided by Python. These functions are already available and can be used directly in a program.

Examples:

  • print()
  • input()
  • len()
  • sum()
  • max()
Example:
    name = "Python"

    print(len(name))
    
Output:
    6
    

User Defined Functions

A user defined function is a function created by the programmer to perform a specific task according to the needs of the program.

These functions are not built into Python and must be defined by the user.

Example:
    def greet():

        print("Welcome to Python")

    greet()
    
Output:
    Welcome to Python
    

Advantages of User Defined Functions

  • Reduce code duplication.
  • Make programs easier to read.
  • Improve code reusability.
  • Simplify testing and debugging.
  • Help divide large programs into smaller modules.

Components of a User Defined Function

A user defined function generally consists of:

  • Function Definition
  • Function Call
  • Return Statement

1. Function Definition

Function definition is the process of creating a function using the def keyword.
The function is only created here. It will not execute until it is called.

2. Function Call

Function call is used to execute the function.

3. Return Statement

The return statement is used to send a value back from the function to the calling statement.


Parameters and Arguments

Parameters and arguments are used to pass data into functions.

Parameters

Parameters are variables listed inside the parentheses while defining a function.

Arguments

Arguments are the actual values passed to the function during the function call.

Program: Find Area of Rectangle Using Function

    def area(length, breadth):
        return length * breadth
    result = area(10, 5)
    print("Area =", result)
    
Output:
    Area = 50
    

Difference Between Library Function and User Defined Function

Library Function User Defined Function
Already provided by Python. Created by the programmer.
Can be used directly. Must be defined before use.
Examples: print(), input(), len() Examples: add(), area(), greet()
Predefined functions. Custom functions.

Practice Programs

      1.  Write a program to calculate the area of a rectangle using a 
user-defined function.
Solution: def area(length, breadth): return length * breadth l = float(input("Enter length: ")) b = float(input("Enter breadth: ")) result = area(l, b) print("Area of Rectangle =", result) Sample Output: Enter length: 10 Enter breadth: 5 Area of Rectangle = 50.0
2. Write a program to calculate the area and volume of a sphere
using a user-defined function.
Formula: Area = 4πr² Volume = (4/3)πr³ Solution: def sphere_area(r): return 4 * (22/7) * r * r def sphere_volume(r): return (4/3) * (22/7) * (r ** 3) r = float(input("Enter radius: ")) a = sphere_area(r) v = sphere_volume(r) print("Area of Sphere =", a) print("Volume of Sphere =", v) Sample Output: Enter radius: 7 Area of Sphere = 616.0 Volume of Sphere = 1437.3333333333333
3. Write a program to display the area and circumference of a
circle using a user-defined function.
Formula: Area = πr² Circumference = 2πr Solution: def area(r): return (22/7) * r * r def circumference(r): return 2 * (22/7) * r r = float(input("Enter radius: ")) a = area(r) c = circumference(r) print("Area =", a) print("Circumference =", c) Sample Output: Enter radius: 7 Area = 154.0 Circumference = 44.0
4. Write a program to display the TSA and LSA of a
room using a user-defined function.
Formula: TSA = 2[lb+bh+lh] LSA = 2h(l+b) Note: This is an assignment practice problem. Do it yourself and consult your teacher, in case you need help.

Different Methods of Function Calling

a) Function with No Arguments and No Return Value

  • Does not receive any data from the user.
  • Does not return any value.
Example:
    def greet():
        print("Welcome to Python")
    greet()
    
Output:
    Welcome to Python
    

b) Function with Arguments and No Return Value

  • Receives data through parameters.
  • Displays the result directly.
Example:
    def square(num):
        print("Square =", num * num)
    square(5)
    
Output:
    Square = 25
    

c) Function with Arguments and Return Value

  • Receives data through parameters.
  • Returns the result using the return statement.
Example:
    def add(a, b):
        return a + b
    result = add(10, 20)
    print(result)
    
Output:
    30
    

d) Function with No Arguments but Return Value

  • Does not receive any arguments.
  • Returns a value.
Example:
    def get_message():
        return "Hello Students"
    msg = get_message()
    print(msg)
    
Output:
    Hello Students
    

Different Types of Arguments in Functions

a) Positional Arguments

Arguments are passed in the same order as parameters.
Example:
    def student(name, age):
        print(name, age)
    student("Ram", 15)
    
Output:
    Ram 15
    

b) Default Arguments

A default value is assigned to a parameter. If no value is passed, the default value is used.
Example:
    def greet(name="Student"):
        print("Hello", name)
    greet()
    greet("Sita")
    
Output:
    Hello Student
    Hello Sita
    

c) Arbitrary Arguments (*args)

Allows passing any number of arguments. Arguments are stored as a tuple. Example:
    def total(*num):
        print(sum(num))
    total(10, 20, 30)
    
Output:
    60
    

d) Keyword Arguments

Arguments are passed using parameter names. Order does not matter.
Example:
    def student(name, age):
        print(name, age)
    student(age=15, name="Ram")
    
Output:
    Ram 15
    

Variable Scope in Python

Variable Scope refers to the area of a program where a variable can be accessed.

a) Local Variable

Declared inside a function. Can only be used within that function.
Example:
    def show():
        x = 10
        print(x)
    show()
    
Output:
    10
    

b) Global Variable

Declared outside all functions. Can be accessed throughout the program.
Example:
    x = 50
    def show():
        print(x)
    show()
    print(x)
    
Output:
    50
    50
    

Practice Programs on User Defined Functions

1. Write a program to calculate simple interest when principle, rate and time is given by the user using function.

Hint: I = PTR/100

Solution:
      def si(p, t, r):
          return (p * t * r) / 100
      p = float(input("Enter principle: "))
      t = float(input("Enter time: "))
      r = float(input("Enter rate: "))
      print("The interest amount is:", si(p, t, r))
      

2. Write a program to check whether the given number is even or odd by using function.

Solution:
      def evenodd(n):
          if n % 2 == 0:
              return "Even"
          return "Odd"
      a = int(input("Enter a number: "))
      print(a, "is an", evenodd(a), "number.")
      

3. Write a program to input Selling Price and Cost Price from the user and calculate the profit amount or loss amount or display neither profit nor loss by using function.

Solution:
      def profitloss(cp, sp):
          if cp > sp:
              return cp-sp
          elif sp > cp:
              return sp-cp
          return "Neither Profit nor Loss"
      cp = float(input("Enter cost price: "))
      sp = float(input("Enter selling price: "))
      if cp < sp:
      	  result="Profit"
      else:
      	  result="Loss"
      print(result," is ",profitloss(cp,sp))
      

4. Write a program to display the factorial of a given number by creating user defined function.

Solution:
      def factorial(n):
          f = 1
          for i in range(1, n + 1):
              f *= i
          return f
      n = int(input("Enter a number: "))
      print("The factorial of", n, "is", factorial(n))
      

5. Write a program to display whether the given number is prime or composite by creating user defined function.

Solution:
      def primecomposite(n):
          c = 0
          for i in range(1, n + 1):
              if n % i == 0:
                  c += 1
          if c == 2:
              return "Prime"
          return "Composite"
      x = int(input("Enter a number: "))
      print(x, "is a", primecomposite(x), "number.")
      

6. Write a program to count the number of consonants present in the given word by using function.

Solution:
      def consonant(word):
          c = 0
          v = "aeiou"
          for ch in word.lower():
              if ch.isalpha() and ch not in v:
                  c += 1
          return c
      word = input("Enter a word: ")
      print("There are", consonant(word), "consonants in the word.")
      

7. Write a program to store five numbers in the list. The program should then display the product of all the numbers by creating user defined function.

Solution:
      def prod(nlist):
          mul = 1
          for i in nlist:
              mul *= i
          return mul
      num = []
      for i in range(5):
          n = int(input("Enter number: "))
          num.append(n)
      print("The product of all the numbers in the list is", prod(num))
      

8. Write a program to input a word from the user. The program should then display the reverse and alternate characters by creating function.

Solution:
      def revalt(word):
          alt = ""
          rev = ""
          for i in range(0, len(word), 2):
              alt += word[i]
          for i in range(-1,-len(word)-1, -1):
              rev += word[i]
          print("The alternate characters are", alt)
          print("The reverse word is", rev)
      word = input("Enter a word: ")
      revalt(word)
      

9. Write a program to calculate the area and volume of a room by returning multiple values in function.

Hint: Area = l × b, Volume = l × b × h

Solution:
      def calculate(l, b, h):
          ar = l * b
          vol = l * b * h
          return ar, vol
      l = float(input("Enter length: "))
      b = float(input("Enter breadth: "))
      h = float(input("Enter height: "))
      area, volume = calculate(l, b, h)
      print("The area is", area)
      print("The volume is", volume)
      

Final Pending Work for this Chapter

Select the Correct Answer from the Given Alternatives

  1. Which of the following statement is false about user defined function in Python?
    Answer: Function never returns value.

  2. Which keyword is used to define a user-defined function in Python?
    Answer: def

  3. What are the variables which appear in the function definition called?
    Answer: Parameters

  4. In which arguments are the values transferred from the arguments to the parameters based on their position?
    Answer: Positional Arguments

  5. Which arguments are used when the number of arguments that have to be passed into a function is not known in advance?
    Answer: Arbitrary Arguments

  6. Which variable has limited scope and cannot be accessed from other parts of the program?
    Answer: Local Variable

  7. Variables declared inside a function have ________.
    Answer: Local Scope

  8. What does the return statement do in a Python function?
    Answer: Sends a value back to the calling function.

Q. Differentiate Between Functions That Return a Value (Non-Void) and Those That Do Not (Void)

Answer:
Non-Void Function Void Function
Returns a value back to the calling function. Does not return any value back to the calling function.
The returned value can be reused in the main program. The result cannot be reused because it is only displayed inside the function.
Uses the return statement. Usually uses print() to display output.
Example:
def sum(a, b):
   return a + b
Example:
def sum(a, b):
   print(a + b)
Function WITH Return

A function with a return statement processes data and sends the resulting value back to the line of code from where it was called.

Function WITHOUT Return

A function without a return statement (also called a void function) performs actions directly such as displaying output, saving data or updating values.