0% found this document useful (0 votes)
8 views8 pages

Unit-2 Functions in Python HPTU

Uploaded by

palakchauhan006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views8 pages

Unit-2 Functions in Python HPTU

Uploaded by

palakchauhan006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Functions in Python:

In Python, functions are blocks of reusable code that perform a specific


task. They help in making code modular, readable, and maintainable. The
function in python is created using the def keyword.

1. Types of Functions in Python


Type Description Example

Built-in Functions Predefined in Python print(), len(), sum(), type(),


input()

User-defined Created by the programmer def greet(): print("Hello")


Functions

Lambda Functions Anonymous functions lambda x: x * x


(one-liners)

Recursive Functions Call themselves Used for factorial, Fibonacci,


etc.

2. Defining a Function
def greet():
print("Hello, world!")

●​ def → keyword to define a function


●​ greet → function name
●​ () → parentheses (can include parameters)
●​ : → colon to start the function block
●​ print("...") → function body (indented)

Void function : In Python, there's no explicit void keyword like in


C/C++. But a void function is one that performs an action (like
printing), but doesn’t return anything.

3. Calling a Function
greet()

4. Function with Parameters and Return


def add(a, b):
return a + b
result = add(5, 3)
print("Sum:", result)

●​ Parameters: a, b
●​ Return: sends back result to the caller

5. Global vs Local variable:

x = 10 # Global variable

def func():

x = 5 # Local variable

print("Inside function:", x)

func()

print("Outside function:", x)

6. Lifetime of Variables
Lifetime is the duration a variable exists in memory.

●​ Global variable: Exists as long as the program runs.


●​ Local variable: Exists only while the function is running.
def test():

x = 100 # Local variable: created when function is called

test()

print(x) ​ ​ # x no longer exists here

Trying print(x) outside the function would give:

NameError: name 'x' is not defined

7. Default Arguments
def greet(name="Guest"):
print("Hello", name)
greet() ​ # Hello Guest
greet("Alex") ​​ # Hello Alice

8. Keyword Arguments: Instead of passing arguments by


position, the arguments are passed using keywords.
def student(name, age):
print(name, "is", age, "years old.")
student(age=20, name="John")

Why Use Keyword Arguments?

●​ Order doesn't matter: You can specify arguments in any order.


●​ Improves readability: It's clear which value is for which parameter.
●​ Avoids mistakes when dealing with functions that have many
parameters.

9. Variable-length Arguments
●​ *args → accepts multiple positional arguments as a tuple
●​ **kwargs → accepts multiple keyword arguments as a
dictionary

def func (*args, **kwargs) :​​ ​ # Function definition


print("Positional:", args)
print("Keyword:", kwargs)

func (1, 2, 3, a="X", b="Y")​​ ​ # Function calling

●​ *args Eg.

def total(*numbers):
return sum(numbers)
print(total(1, 2, 3, 4)) ​ # Output: 10

●​ **kwargs

def info(**var):

for key, value in var.items():

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

info(name="Alice", age=25, city="Delhi")

10. Lambda (Anonymous) Functions


square = lambda x: x * x
print(square(5)) ​ ​ # Output: 25

Used for short, single-expression functions, often in functional


programming (map, filter, reduce).

nums = [1, 2, 3, 4]

squares = list(map(lambda x: x * x, nums))

print(squares) ​ ​ ​ # Output: [1, 4, 9, 16]


nums = [1, 2, 3, 4, 5, 6]

even_nums = list(filter(lambda x: x % 2 == 0, nums))

print(even_nums) ​ ​ # Output: [2, 4, 6]

names = ['Alice', 'Bob', 'Charlie', 'David']

sorted_names = sorted(names, key=lambda x: len(x))

print(sorted_names) ​ # Output: ['Bob', 'Alice', 'David', 'Charlie']

11. Recursive Function Example


Factorial:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) ​​ # Output: 120

Fibonacci:
def fibonacci(n):
"""Return the nth Fibonacci number using
recursion."""
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
n_terms = 10

print("Fibonacci series:")
for i in range(n_terms):
print(fibonacci(i), end=' ')

#Output
Fibonacci series:
0 1 1 2 3 5 8 13 21 34

12. Docstring (Documentation String)


def greet():
"""This function prints a greeting message."""
print("Hello!")
print(greet.__doc__)

Used to describe what a function does. Appears when you use


help().

help(greet)

Docstring vs Comment:

Feature Docstring Comment (#)

Syntax Triple quotes (""" or ''') Starts with #

Use case Documentation for functions/classes Explanatory notes in code

Accessible by help() or .__doc__ Not accessible at runtime

Feature Example

Basic function def func():


Return value return result

Parameters def func(a, b=2):

Variable args *args, **kwargs

Anonymous lambda x: x+1

Recursive func() calls itself

Summary 1 Built‑in and Standard‑Library Functions


Category Where they How you use them A few handy
live examples

Built‑in Loaded Call them directly len(), print(),


functions automatically. range(), sum(),
no import max(), min(),
needed abs()

Standard‑lib Inside modules import math → math.sqrt(16) math, random,


rary that ship with itertools,
functions CPython import datetime → collections, os,
datetime.date.today() pathlib, json

Key points

●​ Always available: You don’t install them separately.


●​ Well‑tested & documented: Ideal first choice before reaching for
external packages.
●​ Performance: Many are implemented in C under the hood, so they’re
fast.

2 User‑Defined Functions
When the built‑ins or the standard library don’t do exactly what you need,
you create your own:

def fahrenheit_to_celsius(f):
"""Convert °F to °C."""
return (f - 32) * 5 / 9
Why define your own?

●​ Reusability – avoid copy‑pasting the same logic.


●​ Readability – a descriptive name hides messy details and clarifies
intent.
●​ Testing – isolating logic in a function makes unit testing trivial.

Combining Built in and User defined function:

import statistics # standard‑library module


def describe(data):
"""Return basic stats for an iterable of numbers."""
return {
"count": len(data), # built‑in len()
"mean": statistics.mean(data), # std‑lib function
"min": min(data), # built‑in min()
"max": max(data), # built‑in max()
}
values = [3, 7, 8, 2, 5]
print(describe(values))

Output

{'count': 5, 'mean': 5, 'min': 2, 'max': 8}

Here you see all three layers working together:

1.​ Built‑ins (len, min, max)


2.​ Standard library (statistics.mean)
3.​ Your own helper (describe)

You might also like