0% found this document useful (0 votes)
2 views16 pages

Unit - 3(Python)

The document provides a comprehensive overview of functions in Python, including their definition, creation, and calling, along with various categories and types of function arguments. It also discusses recursion, modules, and the use of keywords like import, from, and as for managing code. Additionally, it explains how to create a package to organize related modules efficiently.

Uploaded by

sahithichinta45
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)
2 views16 pages

Unit - 3(Python)

The document provides a comprehensive overview of functions in Python, including their definition, creation, and calling, along with various categories and types of function arguments. It also discusses recursion, modules, and the use of keywords like import, from, and as for managing code. Additionally, it explains how to create a package to organize related modules efficiently.

Uploaded by

sahithichinta45
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

[Link] Functions. Explain the Creation and Calling of a Function with Suitable Examples.

Introduction

A function is a named block of code that performs a specific task. Functions help in reducing code repetition,
improving readability, and making programs easier to maintain and reuse.

Advantages of Functions

1. Reduces code duplication.

2. Improves program readability.

3. Makes debugging and testing easier.

4. Promotes code reusability.

5. Makes large programs easier to manage.

Creating a Function

A function is created using the def keyword followed by the function name and parentheses.

Syntax

def function_name():
statements

Example

def greet():
print("Welcome to Python")

Calling a Function

After defining a function, it can be executed by using its name followed by parentheses.

Syntax

function_name()

Example

def greet():
print("Welcome to Python")

greet()

Output

Welcome to Python

Function with Arguments


Arguments are values passed to a function when it is called.

Example

def add(a, b):


print("Sum =", a + b)

add(10, 20)

Output

Sum = 30

Function with Return Value

A function can return a value using the return statement.

Example

def square(n):
return n * n

print(square(5))

Output

25

Explanation

• def is used to define a function.

• Function name identifies the function.

• Arguments allow data to be passed to the function.

• return sends a value back to the caller.

• A function executes only when it is called.

Conclusion

A function is a reusable block of code that performs a specific task. It is created using the def keyword and
executed by calling its name. Functions improve code reusability, readability, and efficiency, making them an
essential part of Python programming.

[Link] the Different Function Categories with Examples

Introduction

A function is a block of reusable code that performs a specific task. Based on the presence of arguments and
return values, functions are classified into different categories.
Types of Functions

1. Function without Arguments and without Return Value

This type of function does not take any input and does not return any value. It simply performs a task.

Syntax

def function_name():
statements

Example

def greet():
print("Welcome to Python")

greet()

Output

Welcome to Python

2. Function with Arguments and without Return Value

This type of function accepts input values (arguments) but does not return any value.

Example

def add(a, b):


print("Sum =", a + b)

add(10, 20)

Output

Sum = 30

3. Function without Arguments and with Return Value

This type of function does not take any input but returns a value.

Example

def value():
return 100

print(value())

Output

100

4. Function with Arguments and with Return Value

This type of function accepts input values and returns a result. It is the most commonly used category.
Example

def multiply(a, b):


return a * b

print(multiply(5, 4))

Output

20

Summary of Function Categories

Function Type Arguments Return Value

Without Arguments & Without Return No No

With Arguments & Without Return Yes No

Without Arguments & With Return No Yes

With Arguments & With Return Yes Yes

Advantages of Functions

1. Reduces code repetition.

2. Improves readability.

3. Makes programs modular.

4. Easier to test and debug.

5. Promotes code reusability.

Conclusion

Functions can be classified into four categories based on the use of arguments and return values: without
arguments and without return value, with arguments and without return value, without arguments and
with return value, and with arguments and with return value. These categories help programmers write
efficient and reusable programs.

[Link] and Explain Various Function Arguments with Suitable Examples

Introduction

Arguments are the values passed to a function when it is called. They allow a function to work with different
data. Python supports different types of function arguments to provide flexibility and simplicity in
programming.

Types of Function Arguments


1. Positional Arguments

Definition

In positional arguments, values are passed to the function in the same order as the parameters defined in the
function.

Example

def student(name, age):


print("Name:", name)
print("Age:", age)

student("Ammu", 18)

Output

Name: Ammu
Age: 18

2. Keyword Arguments

Definition

In keyword arguments, values are passed using parameter names. The order of arguments does not matter.

Example

def student(name, age):


print("Name:", name)
print("Age:", age)

student(age=18, name="Ammu")

Output

Name: Ammu
Age: 18

3. Default Arguments

Definition

A default value is assigned to a parameter. If no value is passed during the function call, the default value is
used.

Example

def greet(name="Ammu"):
print("Hello", name)

greet()

Output
Hello Ammu

4. Variable-Length Arguments

Definition

Variable-length arguments allow a function to accept any number of arguments using *args.

Example

def add(*num):
print(num)

add(10, 20, 30)

Output

(10, 20, 30)

Summary Table

Argument Type Description

Positional Argument Values passed in order

Keyword Argument Values passed using parameter names

Default Argument Uses a default value if no argument is given

Variable-Length Argument Accepts multiple arguments

Conclusion

Python provides Positional Arguments, Keyword Arguments, Default Arguments, and Variable-Length
Arguments. These arguments make functions flexible and easy to use with different types of input values.

[Link] a Function Return Multiple Types of Data? Justify with Suitable Example.

Introduction

A function is a block of code that performs a specific task and returns a result using the return statement. In
Python, a function can return multiple values at a time, and these values can be of different data types such
as integer, string, float, list, etc.

Returning Multiple Values from a Function

Python allows a function to return more than one value by separating them with commas in the return
statement.

Syntax
def function_name():
return value1, value2, value3

Example Program

def student_details():
return 101, "Ammu", 85.5

roll_no, name, marks = student_details()

print("Roll No =", roll_no)


print("Name =", name)
print("Marks =", marks)

Output

Roll No = 101
Name = Ammu
Marks = 85.5

Explanation

In the above program:

• 101 is an integer.

• "Ammu" is a string.

• 85.5 is a float.

The function returns all three values together, and they are stored in separate variables when the function is
called.

Hence, Python functions can return multiple values of different data types.

Advantages

1. Returns multiple results using a single function.

2. Reduces the number of function calls.

3. Makes the program simple and efficient.

4. Improves code readability and reusability.

Conclusion

Yes, a Python function can return multiple types of data. It can return integers, strings, floats, lists, and
other data types together using a single return statement. This makes Python functions flexible and powerful.
[Link] Recursion. Explain with Suitable Program.

Introduction

Recursion is an important concept in Python programming. It is a technique in which a function calls itself
repeatedly to solve a problem. Instead of using loops, a problem is divided into smaller subproblems, and the
same function is used to solve them.

A recursive function must contain a base condition (stopping condition). Without a base condition, the
function will call itself forever and the program may crash.

Definition

Recursion is the process in which a function calls itself directly or indirectly until a specified condition is
satisfied.

A function that calls itself is known as a recursive function.

Components of Recursion

1. Recursive Call

The function calls itself to solve a smaller part of the problem.

2. Base Condition

The condition that stops the recursive calls and prevents infinite execution.

Syntax

def function_name(n):
if condition:
return value
else:
return function_name(smaller_value)

Example: Factorial Using Recursion

Program

def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)

num = 5
print("Factorial =", factorial(num))

Output
Factorial = 120

Working of the Program

When factorial(5) is called:

factorial(5)
= 5 × factorial(4)

= 5 × 4 × factorial(3)

= 5 × 4 × 3 × factorial(2)

= 5 × 4 × 3 × 2 × factorial(1)

=5×4×3×2×1

= 120

Here, factorial(1) returns 1, which is the base condition. After reaching the base condition, the function
returns back step by step and calculates the final answer.

Advantages of Recursion

1. Makes the program shorter and simpler.

2. Easy to understand complex problems.

3. Reduces the need for lengthy loops.

4. Useful in mathematical calculations.

5. Widely used in tree and graph operations.

Disadvantages of Recursion

1. Uses more memory because each function call is stored.

2. Execution may be slower than loops.

3. Incorrect base conditions can cause infinite recursion.

Applications of Recursion

• Finding Factorial of a Number

• Fibonacci Series

• Tree Traversal

• Graph Algorithms
• Mathematical Computations

Conclusion

Recursion is a technique where a function calls itself until a base condition is reached. It helps solve
problems by breaking them into smaller subproblems. Although it uses more memory, recursion makes many
programs simpler and easier to understand.

6. Define Module. Explain Different Built-in Modules with Examples.

Introduction

A module is a file that contains Python code such as functions, variables, and classes. Modules help in
reusing code and make programs easier to develop and manage.

Python provides many built-in modules that contain ready-made functions for performing different tasks.

Definition

A module is a collection of related functions, variables, and classes stored in a single file, which can be used
in other Python programs.

Syntax

import module_name

Advantages of Modules

1. Promotes code reusability.

2. Reduces program length.

3. Makes programs organized and easy to maintain.

4. Saves development time.

5. Provides ready-made functions.

Built-in Modules in Python

1. Math Module

The math module is used for performing mathematical operations.

Example

import math

print([Link](25))

Output

5.0
Uses

• Square root

• Trigonometric functions

• Logarithmic calculations

2. Random Module

The random module is used to generate random numbers.

Example

import random

print([Link](1, 10))

Output

A random number between 1 and 10

Uses

• Games

• Password generation

• Simulations

3. Datetime Module

The datetime module is used to work with dates and time.

Example

import datetime

print([Link]())

Output

Current Date

Uses

• Displaying current date

• Calculating age

• Time-related applications

4. Calendar Module

The calendar module is used to display calendars.

Example
import calendar

print([Link](2026, 6))

Uses

• Display monthly calendars

• Date calculations

Summary of Built-in Modules

Module Purpose

Math Mathematical calculations

Random Generate random numbers

Datetime Work with date and time

Calendar Display calendars

Conclusion

A module is a file containing reusable Python code. Python provides several built-in modules such as Math,
Random, Datetime, and Calendar, which help programmers perform various tasks easily and efficiently.

7. Explain import, from, and as Keywords with Program.

Introduction

Python provides several keywords to use modules in a program. The most commonly used keywords are
import, from, and as. These keywords help programmers access functions, classes, and variables from
modules.

1. import Keyword

Definition

The import keyword is used to import an entire module into a program. After importing, we can access its
functions using the module name.

Syntax

import module_name

Example

import math

print([Link](25))

Output
5.0

Explanation

Here, the math module is imported, and the sqrt() function is accessed using [Link]().

2. from Keyword

Definition

The from keyword is used to import specific functions or variables from a module. This avoids writing the
module name repeatedly.

Syntax

from module_name import function_name

Example

from math import sqrt

print(sqrt(25))

Output

5.0

Explanation

Only the sqrt() function is imported from the math module, so we can directly use sqrt().

3. as Keyword

Definition

The as keyword is used to give an alias (another name) to a module or function. It makes the code shorter and
easier to write.

Syntax

import module_name as alias_name

Example

import math as m

print([Link](25))

Output

5.0

Explanation

The math module is renamed as m, so [Link]() is used instead of [Link]().


Difference Between import, from, and as

Keyword Purpose

import Imports the entire module

from Imports specific functions or variables

as Gives an alias name to a module or function

Advantages

1. Reuse code from existing modules.

2. Reduces program length.

3. Improves readability.

4. Makes programming easier and faster.

Conclusion

The import, from, and as keywords are used to work with modules in Python. import loads the entire module,
from imports specific members, and as provides an alternate name. These keywords help programmers use
modules efficiently and write organized programs.

8. How to Create a Package? Explain with an Example.

Introduction

A package is a collection of related modules organized in a directory (folder). Packages help in organizing
Python programs and managing large projects efficiently.

In Python, a package contains one or more modules and a special file called __init__.py.

Definition

A package is a directory that contains multiple Python modules along with an __init__.py file. It is used to
organize related modules into a single unit.

Advantages of Packages

1. Organizes large programs efficiently.

2. Improves code reusability.

3. Avoids naming conflicts between modules.

4. Makes programs easier to maintain.

5. Simplifies project management.


Steps to Create a Package

Step 1: Create a Package Folder

Create a folder named mypackage.

mypackage

Step 2: Create __init__.py File

Inside the package folder, create a file named __init__.py.

mypackage/
__init__.py

Purpose:

• Identifies the folder as a Python package.

• Allows Python to recognize and import modules from the package.

Step 3: Create a Module

Create a file named [Link] inside the package.

[Link]

def sum(a, b):


return a + b

Package Structure

mypackage/
__init__.py
[Link]

Step 4: Use the Package in a Program

Main Program

from [Link] import sum

print(sum(10, 20))

Output

30

Explanation

• mypackage is the package name.


• [Link] is the module inside the package.

• sum() is the function inside the module.

• The statement

from [Link] import sum

imports the sum() function from the package and allows us to use it in our program.

Applications of Packages

1. Large software projects.

2. Web applications.

3. Data science projects.

4. Machine learning applications.

5. Code organization and maintenance.

Difference Between Module and Package

Module Package

Single Python file Collection of modules

Contains functions and classes Contains multiple modules

Example: [Link] Example: mypackage

Conclusion

A package is a collection of related modules stored in a directory. It helps organize programs, improve code
reusability, and simplify project management. A package is created using a folder containing modules and an
__init__.py file.

You might also like