Sunday, 23 February 2025

Functions in Python

Unit 3 - 3.1 Functions in Python

Functions in Python are reusable blocks of code that perform a specific task. They help make code more organized, readable, and reusable.

Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again.

Some Benefits of Using Functions

  • Increase Code Readability 

Types of Functions in Python

1. Built-in Functions – Predefined functions like print(), len(), type(), etc.

2. User-Defined Functions – Functions created by the user using the def keyword.

3. Lambda Functions – Anonymous, single-expression functions created using the lambda keyword.

4. Recursive Functions – Functions that call themselves to solve problems iteratively.

Defining a Function :A function is defined using the def keyword

python

def greet(name):

    """Function to greet a person"""

    print(f"Hello, {name}!")

 

# Calling the function

greet("Alice")

Function Explanation

  • def – Keyword to define a function.
  • greet – Function name.
  • name – Parameter (input).
  • print(f"Hello, {name}!") – Function body (execution statements).
  • greet("Alice") – Function call.

Function with Return Value : Functions can return values using return

python

def add(a, b):

    return a + b

result = add(5, 3)

print(result)  # Output: 8


Function with Multiple Return Value

python

def calculate(a, b):

sum_value = a + b

diff_value = a - b

product_value = a * b

return sum_value, diff_value, product_value # Returning multiple values as a tuple

 

# Calling the function

result = calculate(10, 5)

# Accessing the returned values

sum_result, diff_result, product_result = result

print("Sum:", sum_result)

print("Difference:", diff_result)

print("Product:", product_result)

 


Default Arguments : Default values can be assigned to parameters

python

def power(base, exp=2):

    return base ** exp

print(power(3))   # Uses default exp=2, output: 9

print(power(3, 3)) # Output: 27


Variable-Length Arguments

1. *args (Non-keyword arguments) – Allows passing multiple values as a tuple.

python

def sum_all(*numbers):

    return sum(numbers)

print(sum_all(1, 2, 3, 4))  # Output: 10

2. **kwargs (Keyword arguments) – Allows passing multiple key-value pairs as a dictionary.

python

def print_info(**info):

    for key, value in info.items():

        print(f"{key}: {value}")

print_info(name="Alice", age=25, city="NY")


Lambda Functions

Short, anonymous functions written using lambda

python

square = lambda x: x ** 2

print(square(5))  # Output: 25


Recursive Functions : A function calling itself

python

def factorial(n):

    if n == 0:

        return 1

    return n * factorial(n - 1)

print(factorial(5))  # Output: 120


Nested Function or Inner Function

A nested function, also called an inner function, is a function defined inside another function. It is used to encapsulate functionality, provide better modularity, and restrict access to certain functionalities within the outer function.

python

def outer_function(message):

    def inner_function():

        print("Message from inner function:", message)

    inner_function()  # Calling the inner function

 

# Calling the outer function

outer_function("Hello, Python!")


Function Scope

1.     Local Scope – Variables declared inside a function.

2.     Global Scope – Variables declared outside functions.

3.     Nonlocal Scope – Used in nested functions.

python

x = 10  # Global variable

def outer():

    x = 5  # Local variable

    def inner():

        nonlocal x

        x += 1

        print(x)  # Output: 6

    inner()

outer()


Python provides many built-in functions that are ready to use without requiring any imports. These functions perform various tasks such as mathematical operations, type conversions, input/output handling, and more.

Common Python Built-in Functions

Mathematical Functions

  • abs(x): Returns the absolute value of x.
  • round(x, n): Rounds x to n decimal places.
  • max(iterable): Returns the maximum value in an iterable.
  • min(iterable): Returns the minimum value in an iterable.
  • sum(iterable): Returns the sum of all elements in an iterable.
  • pow(x, y): Returns x raised to the power of y.

Example:

python

print(abs(-10))       # 10

print(round(3.14159, 2))  # 3.14

print(max([1, 2, 3, 4]))  # 4


Type Conversion Functions

  • int(x): Converts x to an integer.
  • float(x): Converts x to a float.
  • str(x): Converts x to a string.
  • bool(x): Converts x to a boolean.
  • list(iterable): Converts an iterable into a list.
  • tuple(iterable): Converts an iterable into a tuple.
  • set(iterable): Converts an iterable into a set.

Example:

python

print(int("10"))      # 10

print(float("3.14"))  # 3.14

print(str(100))       # '100'

print(list("hello"))  # ['h', 'e', 'l', 'l', 'o']


Input/Output Functions

  • print(value, ...): Displays values on the screen.
  • input(prompt): Accepts user input.
  • len(iterable): Returns the length of an iterable.

Example:

python

name = input("Enter your name: ")

print("Hello,", name)

print(len("Python"))  # 6


Working with Iterables

  • range(start, stop, step): Generates a sequence of numbers.
  • enumerate(iterable): Returns an iterator that yields index-value pairs.
  • zip(iter1, iter2, ...): Combines multiple iterables element-wise.
  • sorted(iterable): Returns a sorted list.
  • reversed(iterable): Returns a reversed iterator.
  • map(function, iterable): Applies a function to each element.
  • filter(function, iterable): Filters elements based on a function.

Example:

python

nums = [1, 2, 3]

squared = list(map(lambda x: x**2, nums))  # [1, 4, 9]

evens = list(filter(lambda x: x % 2 == 0, nums))  # [2]

 

print(squared, evens)


Object Inspection Functions

  • type(obj): Returns the type of an object.
  • id(obj): Returns the memory address of an object.
  • dir(obj): Lists all attributes and methods of an object.

Example:

python

 

x = 10

print(type(x))  # <class 'int'>

print(id(x))    # Memory address of x

print(dir(x))   # List of attributes and methods for an int


File Handling Functions

  • open(filename, mode): Opens a file in a given mode.
  • read(): Reads content from a file.
  • write(text): Writes content to a file.
  • eval()

Example:

python

with open("test.txt", "w") as file:

    file.write("Hello, World!")

 

Data Type-Related Built-in Functions

These functions help with type conversion, checking, and manipulation.

 

Type Conversion Functions

These functions convert values from one data type to another.

Function

Description

int(x)

Converts x to an integer.

float(x)

Converts x to a floating-point number.

str(x)

Converts x to a string.

bool(x)

Converts x to a boolean (True or False).

complex(x, y)

Converts x and y to a complex number (x + yj).

list(iterable)

Converts an iterable to a list.

tuple(iterable)

Converts an iterable to a tuple.

set(iterable)

Converts an iterable to a set.

dict(iterable)

Converts an iterable (like a list of key-value pairs) to a dictionary.


Example

python

print(int("10"))      # 10

print(float("3.14"))  # 3.14

print(str(100))       # '100'

print(bool(0))        # False

print(list("abc"))    # ['a', 'b', 'c']

 

print(tuple([1, 2, 3]))  # (1, 2, 3)

print(set([1, 2, 2, 3]))  # {1, 2, 3}

print(dict([("a",1), ("b", 2)]))  # {'a': 1,'b': 2}




Type Checking Functions

These functions help in checking the type of an object.

Function

Description

type(obj)

Returns the type of an object.

isinstance(obj, class)

Checks if obj is an instance of the given class.

issubclass(sub, sup)

Checks if sub is a subclass of sup.

 

Example

python

x = 10

print(type(x))  # <class 'int'>

print(isinstance(x,int))  # True

print(isinstance(x,float))  # False


class Animal:

pass

 

class Dog(Animal):

pass

 

print(issubclass(Dog,Animal))  # True

 

print(issubclass(Animal,Dog))  # False

 


 Object-Related Built-in Functions

These functions help inspect and manipulate objects.

 

Object Attributes & Methods

Function

Description

dir(obj)

Returns a list of attributes and methods of obj.

id(obj)

Returns the memory address of obj.

hash(obj)

Returns a unique hash value of obj (only for hashable types).

callable(obj)

Checks if obj is callable (like a function).

getattr(obj, name)

Gets the attribute name from obj.

setattr(obj, name, value)

Sets the attribute name of obj to value.

hasattr(obj, name)

Checks if obj has an attribute name.

delattr(obj, name)

Deletes the attribute name from obj.


Example

python

class Sample:

    def __init__(self, value):

        self.value = value

    def show(self):

        print("Value:", self.value)

obj =

Sample(10)

print(dir(obj))  # Lists attributes and methods

 

print(id(obj))   # Memory address of obj

 

print(hash(42))  # Hash value (only for immutable types)

 

print(getattr(obj,"value"))  # 10

 

setattr(obj,"value", 20)

 

print(getattr(obj,"value"))  # 20

 

print(hasattr(obj,"value"))  # True

delattr(obj,"value")

print(hasattr(obj, "value"))  # False


 

Checking If an Object Is Callable

An object is callable if it can be called like a function (e.g., functions, classes with __call__ method).

python

def hello():

 

    return "Hello, World!"

print(callable(hello))  # True

x = 10

print(callable(x))  # False


Summary

Category
Functions
Type Conversion
int(), float(), str(), bool(), complex(), list(), tuple(), set(), dict()
Type Checking type(), isinstance(), issubclass()
Object Inspection dir(), id(), hash(), callable()
Attribute Handling getattr(), setattr(), hasattr(), delattr()

No comments:

Post a Comment

Desktop Virtualisation

Desktop Virtualization ( DV ) Desktop Virtualization ( DV ) is a technique that creates an illusion of a desktop provided to the user. It d...