UNIT IV-FUNCTION IN PYTHON
Unit IV Function in Python.
4.1 Function:
o A function is a block of code which only runs when it is called.
o You can pass data, known as parameters, into a function.
o A function can return data as a result.
o Python Functions is a block of statements that return the specific task.
o The idea is to put some commonly or repeatedly done tasks together.
o writing the same code again and again for different inputs.
o we can do the function calls to reuse code contained in it over and over
again.
Introduction to Function:-
Function help to organize code into logical blocks that perform specific
tasks.
Functions in Python are fundamental building blocks that allow you to
encapsulate code into reusable segments.
They help organize your code, making it more readable, maintainable,
and efficient.
Benefits of Using Functions
a. Code Reuse
b. Reduced code length
c. Increased readability of code
Why Use Functions?
1) Reusability: Write a function once and use it multiple times
throughout your code, which reduces redundancy.
2) Modularity: Break your code into smaller, manageable pieces, making
it easier to understand and maintain.
3) Abstraction: Hide complex logic behind a simple interface.
Prepared By: Tamanna Sayyad
UNIT IV-FUNCTION IN PYTHON
4) Testing and Debugging: Functions can be tested independently,
making it easier to isolate and fix bugs.
Types of Functions in Python
Below are the different types of functions in Python:
1) Built-in library function: These are Standard functions in Python that
are available to use.
2) User-defined function: We can create our own functions based on
our requirements.
Python Function Declaration
The syntax to declare a function is:
4.2 Function definition and calling :
• We can define a function in Python, using the def keyword.
• We can add any type of functionalities and properties to it as we require.
• By the following example, we can understand how to write a function in
Python. In this way we can create Python function definition by using def
keyword.
Prepared By: Tamanna Sayyad
UNIT IV-FUNCTION IN PYTHON
Basic Syntax:
def function_name(parameters):
#statement
return function/expression
Example:
def my_function():
print("Hello from a function")
my_function()
OUTPUT: Hello from a function
Calling a Function in Python: -
To run (or "call") the function, use its name followed by parentheses () and
pass required arguments.
Example:
def greet(name):
print("Hello, " + name + "!")
greet("Alice") # Output: Hello, Alice!
4.3 Function parameters :
In Python, function parameters are the variables listed in a function definition
that accept values (called arguments) when the function is called.
Prepared By: Tamanna Sayyad
UNIT IV-FUNCTION IN PYTHON
Basic Function Parameters:
#Function Define
def greet(name):
print("Hello, " + name + "!")
#Function Calling
greet("Alice") # Output: Hello, Alice!
#Function Parameters
def greet(name):
print(f"Hello, {name}!")
Types of Function Parameters
Python supports several kinds of function parameters:
1. Positional Parameters
Arguments are assigned to parameters in the order they appear.
def add(a, b):
return a + b
add(3, 4) # a=3, b=4
2. Default Parameters
You can provide default values.
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Hello, Guest!
greet("Alice") # Hello, Alice!
Prepared By: Tamanna Sayyad
UNIT IV-FUNCTION IN PYTHON
4.4 Default argument function:
Function Argument:
Arguments are the values passed inside the parenthesis of the function.
A function can have any number of arguments separated by a comma.
In this example, we will create a simple function in Python to check whether
the number passed as an argument to the function is even or odd.
Example:
def evenOdd(x):
if (x % 2 == 0):
print(“Even")
else:
print(“Odd")
# call the function
evenOdd(4)
evenOdd(3)
Output:
Even
Odd
Default Argument:
In Python, default argument values allow you to define functions that can be
called with fewer arguments than they are defined to accept. You do this by
assigning a default value to one or more parameters in the function definition.
Syntax:
def function_name(arg1, arg2=default_value):
# function body
...
Prepared By: Tamanna Sayyad
UNIT IV-FUNCTION IN PYTHON
Example:
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("Alice") # Output: Hello, Alice!
greet("Bob", "Hi") # Output: Hi, Bob!
message has a default value of "Hello".
If greet() is called with only one argument, message will default to
"Hello".
4.5 Variable argument function:
• In Python, variable argument functions allow you to pass a varying
number of arguments to a function. This is done using:
a) *args for positional arguments
b) **kwargs for keyword arguments
a) *args – Variable Positional Arguments
It allows a function to accept any number of positional arguments as a
tuple.
Example:
def print_numbers(*args):
for num in args:
print(num)
print_numbers(1, 2, 3)
Output:
1
2
3
Prepared By: Tamanna Sayyad
UNIT IV-FUNCTION IN PYTHON
b) **kwargs – Variable Keyword Arguments
It allows a function to accept any number of keyword arguments as a
dictionary.
Example:
def print_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")
print_info(Name="Alice", Age=30)
Output:
Name:Alice
Age:30
4.6 in built functions in python:
Python provides a wide variety of built-in functions that are always available
without needing to import any libraries.
These functions help perform common tasks like type conversion, data
manipulation, mathematical operations, and more.
Here’s a categorized list of the most commonly used Python built-in
functions:
Type Conversion Functions
1. int() – Converts to integer
2. float() – Converts to float
3. str() – Converts to string
4. bool() – Converts to boolean
5. list() – Converts to list
6. tuple() – Converts to tuple
7. set() – Converts to set
8. dict() – Converts to dictionary
9. complex() – Converts to complex number
10. ord() – Converts character to Unicode code
11. chr() – Converts Unicode code to character
Prepared By: Tamanna Sayyad
UNIT IV-FUNCTION IN PYTHON
12. hex() – Converts integer to hexadecimal
13. bin() – Converts integer to binary
14. oct() – Converts integer to octal
Iteration & Functional Programming
1. range() – Returns a sequence of numbers
2. enumerate() – Adds counter to an iterable
3. zip() – Aggregates elements from iterables
4. map() – Applies function to every item
5. filter() – Filters items by a function
6. reduce() – (from functools) Reduces iterable to a single value
7. any() – Returns True if any item is True
8. all() – Returns True if all items are True
9. sorted() – Returns a sorted list
10. reversed() – Returns a reversed iterator
Input/Output
1. print() – Prints to console
2. input() – Takes user input
3. format() – Formats a string
Mathematical Functions
1. abs() – Absolute value
2. pow() – Power (xⁿ)
3. round() – Rounds a number
4. divmod() – Returns quotient and remainder
5. sum() – Sums iterable
6. max() – Largest item
7. min() – Smallest item
Type Checking
1. type() – Returns the type of an object
2. isinstance() – Checks object type
3. id() – Returns identity of an object
Prepared By: Tamanna Sayyad
UNIT IV-FUNCTION IN PYTHON
4.7 Scope of variable in python:
• Python Scope:
A variable is only available from inside the region it is created. This is
called scope.
• Local Scope:
A variable created inside a function belongs to the local scope of that
function, and can only be used inside that function.
Example:
A variable created inside a function is available inside that function:
def myfunc():
x = 300
print(x)
myfunc()
Output:300
• Function Inside Function
As explained in the example above, the variable x is not available outside
the function, but it is available for any function inside the function:
Example:
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
Output:300
Prepared By: Tamanna Sayyad
UNIT IV-FUNCTION IN PYTHON
• Global Scope
A variable created in the main body of the Python code is a global
variable and belongs to the global scope.
Global variables are available from within any scope, global and local.
• Example
A variable created outside of a function is global and can be used by
anyone:
x = 300
def myfunc():
print(x)
myfunc()
print(x)
output: 300,300
4.8 Files: Introduction, File path, Types of files, Opening and Closing
files, Reading and Writing files.
Introduction to modules-Creating and using Modules, standard
library modules, Importing modules in python program
Files in Python
Introduction
A file is used to store data permanently on a disk.
Python allows you to create, read, write, and delete files using built-in
functions.
Files are essential for saving program output, logs, configurations, or
large data.
File Path
File paths tell Python where to find or save the file.
Types:
Prepared By: Tamanna Sayyad
UNIT IV-FUNCTION IN PYTHON
o Absolute path: Full path from root (e.g.,
C:\Users\John\[Link])
o Relative path: Relative to the current working directory (e.g.,
data/[Link])
Types of Files
1. Text files – .txt, .csv, .log, etc.
o Contains readable characters.
2. Binary files – .exe, .jpg, .mp3, etc.
o Contains binary data, not human-readable.
Opening and Closing Files
Syntax:
file = open("filename", "mode")
# Do file operations
[Link]()
Common Modes:
'r' – read (default)
'w' – write (overwrites)
'a' – append
'b' – binary mode
'x' – create file (error if exists)
'r+' – read and write
Reading and Writing Files
Reading:
[Link]() # Reads entire file
[Link]() # Reads one line
[Link]() # Reads all lines into a list
Writing:
Prepared By: Tamanna Sayyad
UNIT IV-FUNCTION IN PYTHON
[Link]("Hello!") # Writes a string to the
file
[Link](["One\n", "Two\n"]) # Writes a list
of strings
Modules in Python
Introduction
A module is a file containing Python definitions and functions.
Helps organize and reuse code efficiently.
Creating and Using Modules
1. Create a module (e.g., [Link]):
# [Link]
def greet(name):
print(f"Hello, {name}!")
2. Use in another file:
import mymodule
[Link]("Alice")
Standard Library Modules
Python has many built-in modules you can use directly:
math – math functions
datetime – date and time
random – random number generation
os – file and directory operations
sys – system-specific functions
Example:
import math
print([Link](16)) # Output: 4.0
Prepared By: Tamanna Sayyad
UNIT IV-FUNCTION IN PYTHON
Importing Modules
Ways to import:
import math # Full import
from math import sqrt # Specific function
from math import * # All functions (not
recommended)
import math as m # Alias
Description
Topic
File handling Reading/writing data to files
File modes 'r', 'w', 'a', 'b', etc.
Modules Reusable Python files with functions or variables
Standard modules Built-in: math, os, random, etc.
Import styles import, from, as
Prepared By: Tamanna Sayyad