0% found this document useful (0 votes)
21 views23 pages

Python Functions and Modules Guide

module of python programming language

Uploaded by

umeshpunadiya352
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)
21 views23 pages

Python Functions and Modules Guide

module of python programming language

Uploaded by

umeshpunadiya352
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

Python Functions

• Python Functions are a block of statements that does a specific task.

• The idea is to put some commonly or repeatedly done task 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.


Function Declaration
The syntax to declare a function is:

•def: Starts the function definition.

•function_name: Name of the function.

•parameters: Inputs passed to the function (inside ())


Example: Let’s understand this with a simple example. Here, we define a
function using def that prints a welcome message when called.

def fun():
print("Welcome to Class")

Calling a Function
After creating a function in Python we can call it by using the name of the
functions followed by parenthesis containing parameters of that particular
function. Below is the example for calling def function Python.

def fun():
print("Welcome to Class")

fun() # Driver code to call a function


Create a simple function in Python to check whether the number passed as
an argument to the function is even or odd.

def evenOdd(x):
if (x % 2 == 0):
return "Even"
else:
return "Odd"

print(evenOdd(16))
print(evenOdd(7))
Python Built in Functions
Python provides a lot of built-in functions that ease the writing of code

Function Description Example


print() Displays output to the console print("Hello") → Hello
type() Returns the type of an object type(5) → <class 'int'>
len() Returns the length of an object len("Python") → 6
int("10") → 10, float("10") → 10.0,
int(), float(), str() Converts data types
str(10) → "10"
input() Accepts user input name = input("Enter: ")
sum() Returns the sum of elements in an iterable sum([1,2,3]) → 6
min() / max() Returns the minimum/maximum element min([1,2,3]) → 1, max([1,2,3]) → 3
abs() Returns the absolute value abs(-7) → 7
Rounds a number to nearest integer or decimal
round() round(3.456,2) → 3.46
places
Returns a sorted list
sorted() sorted([3,1,2]) → [1,2,3]
from an iterable
list(), tuple(), set(), Converts data to list, list((1,2)) → [1,2], tuple([1,2])
dict() tuple, set, or dictionary → (1,2)
Returns a sequence of
range() list(range(3)) → [0,1,2]
numbers
Returns index and value list(enumerate(['a','b'])) →
enumerate()
pair from iterable [(0,'a'),(1,'b')]
Returns True if all
all() all([True,False]) → False
elements are True
Returns True if any
any() any([True,False]) → True
element is True
Combines two or more list(zip([1,2],[3,4])) →
zip()
iterables [(1,3),(2,4)]
Python Lambda Functions
Lambda Functions are anonymous functions means that the
function is without a name. As we already know def keyword is
used to define a normal function in Python. Similarly, lambda
keyword is used to define an anonymous function in Python.
Example: In the example, we defined a lambda function (upper) to
convert a string to its upper case using upper().

s1 = ‘what is your name’ Syntax


s2 = lambda func: [Link]()
lambda arguments : expression
print(s2(s1))
Use Cases of Lambda Functions

1. Using with Condition Checking

Example 1: Here, the lambda function uses nested if-else logic to classify
numbers as Positive, Negative or Zero.

n = lambda x: "Positive" if x > 0 else "Negative" if x < 0 else "Zero"

print(n(5))
print(n(-3))
print(n(0))
Example 2: This lambda checks divisibility by 2 and returns
"Even" or "Odd" accordingly.

check = lambda x: "Even" if x % 2 == 0 else "Odd"

print(check(4))
print(check(7))
Difference Between lambda and def Keyword
In Python, both lambda and def can be used to define functions, but they
serve slightly different purposes. While def is used for creating standard
reusable functions, lambda is mainly used for short, anonymous functions that
are needed only temporarily.

# Using lambda
sq = lambda x: x ** 2
print(sq(3))

# Using def
def sqdef(x):
return x ** 2
print(sqdef(3))
Python Modules
Python Modules
1. A Python module is a file containing Python definitions and statements.
A module can define functions, classes, and variables. A module can
also include runnable code.

2. Grouping related code into a module makes the code easier to


understand and use. It also makes the code logically organized.
Create a Python Module
To create a Python module, write the desired code and save that in
a file with .py extension.

Example:
Let's create a simple [Link] in which we define two functions,
one add and another subtract.
# A simple module, [Link]
def add(x, y):
return (x+y)

def subtract(x, y):


return (x-y)
Import module in Python
We can import the functions, and classes defined in a module to another
module using the import statement in some other Python source file.
When the interpreter encounters an import statement, it imports the module
if the module is present in the search path.

Syntax to Import Module in Python

import module
Note: This does not import the functions or classes directly instead imports the
module only. To access the functions inside the module the dot(.) operator is
used.
# importing module [Link]
import calc

print([Link](10, 2))
Renaming the Python Module

We can rename the module while importing it using the keyword.

Syntax: Import Module_name as Alias_name

# importing module [Link]


import calc as C
Python Packages
1. Python packages are a way to organize and structure code by grouping
related modules into directories. A package is essentially a folder that
contains an __init__.py file and one or more Python files (modules).
2. This organization helps manage and reuse code effectively, especially in
larger projects.
3. It also allows functionality to be easily shared and distributed across
different applications.
4. Packages act like toolboxes, storing and organizing tools (functions and
classes) for efficient access and reuse.
Step Description Example/Action
Create a Folder
1 Create folder mypackage/
(Package Name)
Create files like
Add Python Module
2 math_operations.py,
Files
string_operations.py inside mypackage/

Write Functions in Example in math_operations.py:


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

Create empty file: mypackage/__init__.py


4 Add __init__.py file
(Marks it as a package)

Use Package in In [Link]:


5 from mypackage import math_operations
Another File print(math_operations.add(5,3))
Create a Package geometry with Modules for Area and Perimeter

Step 1: Directory Structure Step 3: [Link]

geometry/ # [Link]

__init__.py def perimeter_rectangle(length, breadth):


[Link] return 2 * (length + breadth)
[Link]
def perimeter_circle(radius):
return 2 * 3.1416 * radius
Step 2: [Link]
# [Link]

def area_rectangle(length, breadth):


return length * breadth

def area_circle(radius):
return 3.1416 * radius * radius
Step 4: Use the Package in Another Script

import [Link] as area


import [Link] as perimeter
print("Area of rectangle (5 x 3):", area.area_rectangle(5, 3))
print("Area of circle (radius 7):", area.area_circle(7))
print("Perimeter of rectangle (5 x 3):", perimeter.perimeter_rectangle(5, 3))
print("Perimeter of circle (radius 7):", perimeter.perimeter_circle(7))
Module Name Description Example Usage
Provides mathematical functions (sqrt, import math
math
sin, pi, etc.) [Link](16) → 4.0
Provides functions to interact with the import os
os
operating system [Link]() → Current directory

Provides access to system-specific import sys


sys
parameters and functions [Link] → Python version

Generates random numbers and import random


random
performs random operations [Link](1,10) → random int
import datetime
datetime Work with dates and times [Link]() → Current
datetime
import time
time Provides time-related functions
[Link](1) → Pause for 1 second
Import Type Example Syntax Description
import mymodule Import your own .py file (in
Own Module
[Link]("Alice") same directory)
Built-in import math Use standard Python modules
Module [Link](16) like math, os
External import numpy as np Use third-party modules
Module [Link]([1,2,3]) installed via pip
Example: Using math Module for Simple Mathematical Calculations

import math

# Calculate square root of a number


num = 16
sqrt_value = [Link](num)

# Calculate factorial of a number


fact_value = [Link](5)

# Print results
print("Square root of 16:", sqrt_value)
print("Factorial of 5:", fact_value)

You might also like