Learn Python Functions & Modules: Reusable Code and Libraries - Textnotes

Learn Python Functions & Modules: Reusable Code and Libraries


Master Python functions, arguments, lambda expressions, and built-in functions. Learn to organize code with modules, packages, and explore the Python standard library for practical programming.

Objective:

Write reusable, modular Python code using functions and modules. Learn to handle arguments, return values, lambda expressions, and leverage Python’s built-in modules and standard library.

Topics and Examples:

1. Defining Functions using def

Functions allow grouping code into reusable blocks.

Example:


def greet(name):
print(f"Hello, {name}!")

greet("Chinmaya") # Output: Hello, Chinmaya!

2. Function Arguments

Python supports multiple types of arguments:

Positional Arguments:


def add(a, b):
return a + b

print(add(5, 3)) # 8

Keyword Arguments:


def greet(name, message):
print(f"{message}, {name}!")

greet(name="Chinmaya", message="Hello") # Hello, Chinmaya!

Default Arguments:


def greet(name, message="Hi"):
print(f"{message}, {name}!")

greet("Chinmaya") # Hi, Chinmaya!

Arbitrary Arguments (*args and **kwargs):


def sum_numbers(*args):
return sum(args)

print(sum_numbers(1, 2, 3, 4)) # 10

def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

print_info(name="Chinmaya", age=25)

3. Return Values

Functions can return results using the return statement.

Example:


def square(num):
return num ** 2

result = square(5)
print(result) # 25

4. Lambda Functions

Lambda functions are small anonymous functions defined in a single line.

Example:


square = lambda x: x ** 2
print(square(6)) # 36

add = lambda a, b: a + b
print(add(4, 5)) # 9

5. Built-in Functions

Python provides many built-in functions:


# len()
fruits = ["apple", "banana", "cherry"]
print(len(fruits)) # 3

# range()
for i in range(3):
print(i)

# type()
num = 10
print(type(num)) # <class 'int'>

# enumerate()
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(index, color)

6. Modules & Packages

Modules help organize code into separate files; packages group modules.

Import a module:


import math
print(math.sqrt(16)) # 4.0

from math import pi
print(pi) # 3.141592653589793

7. Standard Library Overview

Python comes with a rich standard library:

  1. math: Mathematical functions (sqrt, ceil, floor)
  2. random: Generate random numbers (randint, choice)
  3. datetime: Work with dates and times (datetime.now())
  4. os: Interact with operating system (os.listdir())
  5. sys: Access system-specific parameters (sys.version)

Example:


import random
print(random.randint(1, 10)) # Random number between 1 and 10

import datetime
print(datetime.datetime.now()) # Current date and time

This section covers all essentials of Python Functions & Modules with examples to help learners write reusable, organized code and use standard libraries efficiently.