0% found this document useful (0 votes)
14 views14 pages

Python Functions: Definition & Usage

The document provides an overview of functions in Python, including their definition, types, and usage. It covers topics such as defining functions, calling them, using arguments, and the importance of modular design for code organization. Additionally, it discusses variable scope, standard library modules, lambda functions, and the concept of packages in Python.

Uploaded by

giridharkrishna8
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)
14 views14 pages

Python Functions: Definition & Usage

The document provides an overview of functions in Python, including their definition, types, and usage. It covers topics such as defining functions, calling them, using arguments, and the importance of modular design for code organization. Additionally, it discusses variable scope, standard library modules, lambda functions, and the concept of packages in Python.

Uploaded by

giridharkrishna8
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

Python - Functions

Defining and calling functions


A function is a reusable block of code that performs a specific task.

Functions help you organize your code, avoid repetition, and make it more
readable and modular

Why use Functions?

Code reuse — write once, use many times.

Modular design — break problems into smaller tasks.

Easier debugging and maintenance.

Defining a Function
You define a function in Python using the def keyword.

Syntax :

def function_name(parameters):
"""Optional docstring describing the function."""
# code block
return value

Function with No Arguments

def greet():
print("Hello, welcome to Python!")

greet()

Hello, welcome to Python!

Calling a Function
Simply use the function name followed by parentheses ( () ), passing
arguments if required.

Python - Functions 1
def add(x, y):
return x + y

result = add(5, 3)
print("Sum:", result)

Sum: 8

def student(name, age):


print(f"Name: {name}, Age: {age}")

name_input = input("Enter Name : ")


age_input = int(input("Enter Age : "))
student(name_input, age_input)

Types of Functions
✅ Without arguments, without return
✅ With arguments, without return
✅ With arguments, with return
✅ Without arguments, with return
Function Without arguments, without return

def greet():
print("Hello, welcome to Python!")

greet()

Hello, welcome to Python!

Function Without arguments, with return

import random

Python - Functions 2
def get_random_number():
"""
This function generates a random integer between 1 and 100
and returns it. It takes no arguments.
"""
random_num = [Link](1, 100)
return random_num

# Call the function and store the returned value


number = get_random_number()
print(f"Here's a random number: {number}")

# Call the function multiple times to see different results


print(f"Another random number: {get_random_number()}")

Function With arguments, without return

This type of function takes one or more input values (arguments) to


perform its task, but it doesn't send any value back to the calling code.

def add_and_print(num1, num2):


"""
This function takes two numbers as arguments, calculates their sum,
and prints the result. It does not return any value.
"""
sum_result = num1 + num2
print(f"The sum of {num1} and {num2} is: {sum_result}")

# Call the function with arguments


add_and_print(10, 5)
add_and_print(-3, 7)

Function With arguments, with return

def multiply(a, b):


"""
This function takes two numbers as arguments, calculates their product,
and returns the result.
"""

Python - Functions 3
product = a * b
return product

# Call the function and store the returned value


result1 = multiply(4, 6)
print(f"The product of 4 and 6 is: {result1}")

# Call the function and use the returned value directly


print(f"The product of 7 and 3 is: {multiply(7, 3)}")

Default Arguments
You can provide default values for parameters:

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

greet() # uses default


greet("Alice") # overrides default

Output:

CopyEdit
Hello, Guest!
Hello, Alice!

Keyword Arguments
You can pass arguments by name:

def student(name, age):


print(f"Name: {name}, Age: {age}")

student("tom", 20)

Output:

Python - Functions 4
Name: Tom, Age: 20

Variable-length Arguments
Use *args for any number of positional arguments, and **kwargs for keyword
arguments.

Example:

def display(*args, **kwargs):


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

display(1, 2, 3, name="Tom", age=20)

Output:

Positional: (1, 2, 3)
Keyword: {'name': 'Tom', 'age': 20}

📝 Key Points
✅ Use to define a function.
def

✅ Call the function by its name.


✅ Use to send back a value (optional).
return

✅ Arguments can be required, default, variable-length, or keyword-based.


🧭 Summary Table
Feature Example

Define a function def func():

Call a function func()

Return a value return x

Default argument def func(x=0):

Keyword arguments func(x=5, y=10)

Python - Functions 5
Feature Example

Variable-length args *args , **kwargs

Scope of Variables in Python


In Python, the scope of a variable refers to the part of the program where the
variable is accessible.

There are two main types of scopes:


✅ Local scope
✅ Global scope
Understanding variable scope is important for writing bug-free, predictable
code.

Local Variables
A local variable is a variable that is declared inside a function and can only be
used inside that function.
It exists only while the function runs.

Example:

def greet():
message = "Hello!" # local variable
print(message)

greet()
# print(message) # ❌ Error: message is not defined outside
Output:

Hello!

✅ message exists only inside greet() — you cannot access it outside.

Python - Functions 6
Global Variables
A global variable is a variable that is declared outside any function.
It can be accessed inside and outside of functions.

Example:

name = "Python" # global variable

def show():
print("Language:", name)

show()
print("Outside function:", name)

Output:

Language: Python
Outside function: Python

✅ name is accessible everywhere in the script.

Standard Library Modules in Python


Python comes with a vast collection of built-in modules, known as the
Standard Library, which provides ready-to-use functionality for many common
tasks.
You don’t need to install anything — just import and use!

Why use Standard Library Modules?


✅ Save time — no need to reinvent the wheel
✅ Reliable and tested
✅ Covers a wide range of use cases (math, file handling, dates, random
numbers, etc.)

Python - Functions 7
Examples of Common Standard Library Modules

math Module
The math module provides mathematical functions like square root, power,
trigonometry, constants, etc.
Example:

import math

print([Link](16)) # 4.0
print([Link](5)) # 120
print([Link](2, 3)) # 8.0
print([Link]) # 3.141592653589793

✅ Use when you need precise mathematical calculations.


random Module
The random module is used to generate random numbers and make random
selections.

Example:

import random

print([Link](1, 10)) # random integer between 1 and 10


print([Link](['red', 'blue', 'green'])) # random choice from a list
print([Link]()) # random float between 0.0 and 1.0
print([Link](1.5, 5.5)) # random float between 1.5 and 5.5

lst = [1, 2, 3, 4, 5]
[Link](lst) # shuffle list elements
print(lst)

✅ Useful for games, simulations, and randomized algorithms.


Python - Functions 8
Other Useful Standard Modules

Module Purpose / Usage


datetime Work with dates and times
os Interact with the operating system (e.g., file paths, directories)
sys Access Python runtime environment
statistics Mean, median, mode, standard deviation
json Work with JSON data
time Time-related functions (delays, timestamps)
re Regular expressions for pattern matching
collections Advanced data structures (Counter, defaultdict, namedtuple)

Lambda Functions in Python


A lambda function in Python is a small, anonymous (unnamed) function that
can have any number of arguments but only one expression.

It is also called an inline function.


✅ Lambda functions are useful when you need a quick, throwaway function,
often used as an argument to higher-order functions like map() , filter() , and
sorted() .

Syntax

lambda arguments: expression

✅ lambda — keyword to define the function

✅ arguments — one or more inputs


✅ expression — a single expression to compute and return

Examples of Lambda Functions

Simple Example

Python - Functions 9
square = lambda x: x**2
print(square(5))

Output:

25

With Multiple Arguments

add = lambda x, y: x + y
print(add(3, 7))

Output:

10

No Arguments

greet = lambda: "Hello!"


print(greet())

Output:

Hello!

Python - Functions 10
Where are Lambda Functions Used?
✅ Lambda functions are often used with higher-order functions — functions
that take other functions as arguments.

With map()
Applies a function to all elements in a sequence.

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

Output:

[1, 4, 9, 16]

With filter()
Filters elements based on a condition.

nums = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even)

Output:

[2, 4, 6]

Python - Functions 11
Packages in Python
A package is a way of organizing related modules into a single directory
hierarchy.
✅ A module is a single file.
.py

✅ A package is a folder containing one or more modules and an __init__.py file.


Packages help you organize large projects by grouping related modules
together.

Why use Packages?


✅ Organize code logically
✅ Avoid name conflicts
✅ Make code reusable and maintainable
✅ Useful for distributing libraries
Structure of a Package
A package is simply a folder with this structure:

mypackage/

├── __init__.py
├── [Link]
├── [Link]
└── subpackage/
├── __init__.py
└── [Link]

✅ The file is required (in Python < 3.3) to tell Python this folder is a
__init__.py

package.
✅ It can be empty, or can initialize variables or imports.
Creating a Package
✅ Step 1: Create a folder (e.g., mypackage )

Python - Functions 12
✅ Step 2: Inside the folder, create __init__.py

✅ Step 3: Add your modules (e.g., [Link] , [Link] )

Using a Package
✅ Import modules from the package using dot notation:
import mypackage.module1

mypackage.module1.my_function()

✅ Or import specific functions or classes:


from mypackage.module1 import my_function

my_function()

✅ Or import a subpackage:
import [Link].module3

__init__.py Role
✅ Marks the folder as a package
✅ Can include initialization code or import specific components:
# mypackage/__init__.py
from .module1 import my_function

Now you can directly do:

Python - Functions 13
from mypackage import my_function

my_function()

Advantages of Packages
✅ Better code organization
✅ Makes sharing and distribution easier
✅ Supports hierarchical project structures

Python - Functions 14

You might also like