Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
45 views

Python Notes

Functions in Python allow for code reuse and modular programming. A function is defined using the def keyword and can accept parameters. Functions can return multiple values using tuples, lists, dictionaries, or sets. Variables inside functions have local scope while global variables can be accessed from anywhere. Functions provide modularity and make programs more readable and maintainable.

Uploaded by

Swarali Pawar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Python Notes

Functions in Python allow for code reuse and modular programming. A function is defined using the def keyword and can accept parameters. Functions can return multiple values using tuples, lists, dictionaries, or sets. Variables inside functions have local scope while global variables can be accessed from anywhere. Functions provide modularity and make programs more readable and maintainable.

Uploaded by

Swarali Pawar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Functions:-

• Function is a block of organized, reusable code.


• It performs a specific task or set of tasks, often with a
specific purpose.

Advantages of Functions:-
1. Once defined, Python functions can be called multiple times
and from any location in a program.
2. Our Python program can be broken up into numerous, easy-
to-follow functions if it is significant.
3. The ability to return as many outputs as we want using a
variety of arguments is one of Python's most significant
achievements.

Syntax:-
def function_name(parameters):
# code block
Function Calling:
• To call a function, simply write that function's
name followed by parenthesis(), and by placing
required arguments within the parenthesis.
• Eg
def greet():
print("Hello, world!")

greet()
# Output: Hello, world!
Function Arguments and Parameter:

Parameters:
• Parameters are variables that are used in the
function definition.
• They act as placeholders for the values that will be
passed to the function when it is called.
• Parameters are specified in the function signature.
Arguments:
• Arguments are the actual values or expressions
that are passed to a function when it is called.
• They are the values assigned to the parameters
during the function call.
• Arguments are specified in the function call.
Function Arguments and Parameter:

• Eg
def check_even_odd(num):
if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")

check_even_odd(15)
check_even_odd(20)

#15 is odd
#20 is even
Return Statement:
• The keyword ‘return’ is used to return value.
• The ‘return’ statement in Python is used in a function to
send a value back to the caller.
• It is not mandatory to have a return statement in every
function, but if return statement is used then it must be
the last statement of Python function.
• Because a function is considered as terminated when
return statement appears in a function.
• Eg def add_numbers(x, y):
result = x + y
return result
sum_result = add_numbers(3, 5)
print(sum_result) # Output: 8
Return multiple values:
• functions can return multiple values also. It is done by
same return statement but followed by values to be
returned separated by comma (,).
• Eg def function():
a=10
b=10
return a,b
x = function()
print("Output multiple values: ", x)
print("Output type: ",type(x))

#Output multiple values: (10, 10)


Output type: <class 'tuple'>
Return multiple values using a list:
• lists can also be used to return multiple values
in python.
• Eg def function():
a=10; b=10
return [a,b]
x = function()
print("Output multiple values: ", x)
print("Output type: ",type(x))

#Output multiple values: [10, 10]


#Output type: <class 'list'>
Return multiple values using a dictionary:

• You can also return multiple values from a function using


a dictionary.
• Eg def function():
d = dict()
a, b, c = 10, 20, 30
d['a'] = a
d['b'] = b
d['c'] = c
return d
x = function()
print("Output multiple values:", x)
print("Output type:", type(x))
#Output multiple values: {'a': 10, 'b': 20, 'c': 30}
#Output type: <class 'dict'>
Return multiple using a set :
• You can also return multiple values from a function using
a set.
• Eg def function():
my_set = set()
a, b, c = 10, 20, 30
my_set.add(a)
my_set.add(b)
my_set.add(c)
return my_set
x = function()
print("Output multiple values:", x)
print("Output type:", type(x))
#Output multiple values: {10, 20, 30}
#Output type: <class 'set'>
Scope of Variables:
• The scope of a variable refers to the region of the
program where the variable can be accessed or
modified.
• The scope of a variable is determined by where it
is defined.

Local Variables:
• Variables defined inside a function have local
scope.
• They are accessible only within the function where
they are defined.
• They are created when the function is called and
destroyed when the function exits.
Scope of Variables:
• Eg
def my_function():
x = 10
print("Inside the function:", x)
my_function()

• Global Variables :
• Variables defined outside of any function or block have
global scope.
• They are accessible from any part of the code, both
inside and outside functions.
Scope of Variables:
• Eg:- z = 15
def my_function():
print(z)
my_function()
• if you want to declare a variable as global within a
function you need to use the ‘global’ keyword.
• Eg:- global_variable = 10
def my_function():
global global_variable
global_variable += 1
my_function()
print(global_variable) # Output will be 11
Scope of Variables:
• Enclosing (Non-local) Variables :
• When a function is defined inside another function, the
inner function can access variables from the outer
function.
• Eg
def outer_function():
y=5
def inner_function():
print(y)
inner_function()
outer_function() #5
Function with Default Arguments/Parameters:

• Functions can have optional parameters, also called


default arguments/parameters.
• Default parameters are parameters, which don't have to
be passed, when the function is called.
• In such case, the default values are used. We will
demonstrate the operating principle of default
parameters.
• Eg def sayHello(name="Everyone"):
print("Hello", name, "!")

sayHello("Deepak") # Hello Deepak !


sayHello() # Hello Everyone !
Keyword Arguments OR kwargs:

• In Python, keyword arguments allow you to pass values to


a function by explicitly specifying the parameter names
along with the values.
• This provides clarity and flexibility in function calls,
especially when dealing with functions that have a large
number of parameters.
• Eg: def sample_function(para1, para2, para3):
print("Parameter-1 received:", para1)
print("Parameter-2 received:", para2)
print("Parameter-3 received:", para3)
sample_function(para2=10, para1=True, para3=74.11)
#Output:
#Parameter-1 received: True
#Parameter-2 received: 10
#Parameter-3 received: 74.11
Variable Length Arguments:
• In Python, you can use variable-length arguments when
defining a function to allow it to accept a variable number
of arguments.
• There are two types of variable-length arguments:
1. Arbitrary Positional Arguments (*args) :-
• Allows a function to accept any number of positional
arguments.
• The ‘*args’ syntax collects the additional positional
arguments into a tuple.
• Eg:- def example_function(*args): #Output
for arg in args: #1
print(arg) #2
example_function(1, 2, "three", 4) #three #4
Variable Length Arguments:
2. Arbitrary Keyword Arguments(**kwargs):-
• Allows a function to accept any number of keyword
arguments.
• The ‘**kwargs’ syntax collects the additional keyword
arguments into a dictionary.
• Eg:- def example_function(**kwargs):
for key, value in kwargs.items():
print(key, ":", value)
example_function(name="John", age=25, city="New
York")
#name : John
#age : 25
#city : New York
Variable Length Arguments:

• Eg def example_function(*args, **kwargs):


for arg in args:
print(arg)
for key, value in kwargs.items():
print(key, ":", value)
example_function(1, 2, "three", name="Alice",
age=30)
#1
#2
#three
#name : Alice
#age : 30
Nested Function OR Inner Functions:-
• Python allows nested functions, also known as inner
functions.
• This means you can define a function inside another
function.
• The inner function is only accessible within the scope of
the outer function.
• Eg :- def outer_function():
print("This is outer function.")
def inner_function():
print("This is inner function.")
inner_function()
outer_function()
Pass by Value & Pass by Reference:

1. Pass by Value:-
• When you pass an immutable object (e.g.,
numbers, strings, or tuples) to a function, a
new reference to the object is created
inside the function. Changes made to the
reference inside the function do not affect
the original object outside the function.
• A copy of that value is made and passed to
the function. Modifying the copy within the
function does not affect the original value.
Pass by Value & Pass by Reference:
• Eg def val(x):
x = 15
print(x)
x = 10
val(x) #15
print(x) #10

A new object is created in the memory


because integer objects are immutable (not
modifiable).
Pass by Value & Pass by Reference:

2. Pass by Reference:-
• When you pass a mutable object (e.g., a list,
dictionary) to a function, you are passing a
reference to that object. Changes made to the
object inside the function will affect the original
object outside the function.
• A reference or pointer to the original object is
passed to the function. As a result, any
modifications made within the function directly
impact the original object itself.
Pass by Value & Pass by Reference:
• Eg def val(I):
I.append(4)
print(I)
lst = [1, 2, 3]
print(lst) #[1, 2, 3]
val(lst) #[1, 2, 3, 4]
print(lst, ) #[1, 2, 3, 4]

• A new object is not created in the memory


because list objects are mutable (modifiable). It
simply add new element to the same object.
Python Built-in Functions

• Datatype and object related


Python Built-in Functions:

• Data Conversion functions:-


Python Built-in Functions:-
• Input-Output related:-

• Files and Expression related:-


Python Built-in Functions:

• Class and Inheritance related:-


Python Built-in Functions:

• Mathematical Function:-
Python Modules:

• A document with definitions of functions


and various statements written in Python is
called a Python module.
• A module is a piece of software that has a
specific functionality. Each module is a
different file, which can be edited
separately.
• Modules provide a means of collecting sets
of Functions together so that they can be
used by any number of programs.
Creating Modules:
• To create a module, you simply write Python code in a
‘.py’ file. For example, if you have a file named
‘mymodule.py’, it can be imported as a module using
‘import mymodule’.
• Eg def add(x, y):
return x + y

def subtr(x, y):


return x - y

def mult(x, y):


return x * y

def div(x, y):


return x / y
Importing Modules:

• We can import a module using the import


statement and access the definitions inside
it using the dot operator.
• The ‘import’ statement is used to bring
modules or specific attributes (functions,
classes, or variables) from modules into the
current namespace, allowing you to use
them in your code.
• To access functions or attributes within this
module, you use dot notation:
Importing Modules:
• Eg import mymodule

result_addition = mymodule.add(5, 3)
result_subtraction = mymodule.subtr(10, 4)
result_multiplication = mymodule.mult(6, 7)
result_division = mymodule.div(20, 5)

print("Result of addition:", result_addition)


print("Result of subtraction:", result_subtraction)
print("Result of multiplication:", result_multiplication)
print("Result of division:", result_division)
#Output
Result of addition: 8
Result of subtraction: 6
Result of multiplication: 42
Result of division: 4.0
Import with Renaming:

• Importing specific attributes with renaming allows


you to import a specific attribute from a module
and assign it an alias, making it easier to refer to
in your code.
• We can import a module by renaming it as follows:
# import module by renaming.

import mymodule as m
result_addition = m.add(5, 3)
print("Result of addition:", result_addition)
from...import Statement:
• We can import specific attribute/member
from a module without importing the
module as a whole.
• Eg from mymodule import add, subtr
result = add(2,5)
print(result)
print(subtr(5,3))
#Output
#7
#2
Import everything using *
• To import all the objects from a module within
the present namespace, use the * symbol and
the from and import keyword.
• Eg from mymodule import *
result = add(2,5)
print(result)
print(subtr(5,3))
print(div(30,3))
#Output
#7
#2
#10.0
Importing Multiple Modules:

• You can use multiple import statements or


combine them into a single import
statement.
• Eg 1. import module1
import module2
import module3
• Eg 2. import module1, module2, module3
Python built-in Modules:
• Python’s built-in modules are a set of libraries that
come pre-installed with the Python installation.
• Eg: 1. decimal
2. fractions
3. math
4. operator
5. random
Functional Programming Module:
1. Lambda Expression:
• Lambda functions in Python are anonymous functions
that can be defined using the ‘lambda’ keyword.
• They are typically used for short, simple operations
where a full function definition is unnecessary.
• Lambda functions can take any number of arguments,
but they can only have one expression.
• Syntax:- lambda arguments: expression
• Eg: square = lambda x: x ** 2
print(square(5)) # Output: 25
Functional Programming Module:

2. Map Function:
• The ‘map()’ function in Python is a built-in
function used to apply a given function to
each item of an iterable (like a list, tuple, or
dictionary) and return a map object, which
is an iterator.
• Syntax: map(function, iterable)
Functional Programming Module:

• Eg: def square(x):


return x ** 2
numbers = [1, 2, 3, 4, 5]
result = map(square, numbers)
squared_numbers = list(result)
print(squared_numbers)
# Output: [1, 4, 9, 16, 25]
Functional Programming Module:

3. Filter Function:
• The ‘filter()’ function in Python is another
built-in function that allows you to filter
elements from an iterable (like a list, tuple,
or dictionary) based on a specified function
and returns an iterator of the elements for
which the function returns ‘true’.
• Syntax: filter(function, iterable)
Functional Programming Module:

• Eg: def is_even(x):


return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = filter(is_even, numbers)
even_numbers = list(result)
print(even_numbers)
# Output: [2, 4, 6, 8, 10]
Functional Programming Module:

4. Reduce Function:
• The ‘reduce’ function in Python is used to apply a
function to a sequence (such as a list) cumulatively
to reduce the sequence to a single value.
• It is part of the ‘functools’ module in Python 3 and
above and must be imported before use.
• Syntax: from functools import reduce
result = reduce(function, sequence)
Functional Programming Module:

• Eg from functools import reduce


def add(x, y):
return x + y
numbers = [1, 2, 3, 4, 5]
sum_of_numbers = reduce(add,
numbers)
print(sum_of_numbers)
# Output: 15 (1 + 2 + 3 + 4 + 5 = 15)
Namespace in Scoping:

• In Python, a namespace is a mapping from names


(identifiers) to objects. It provides a way to avoid
name conflicts and organize the code logically.
• Namespaces are crucial for understanding variable
scope, module organization, and the functioning
of Python's import system.
1. Local Namespace:
This namespace includes local names inside a
function or method. It's created when the function is
called and is deleted when the function exits.
Namespace in Python:

2. Global Namespace:
This namespace includes names from various
imported modules that are accessible throughout the
module. It's created when the module is imported
and lasts until the script ends.

3. Built-in Namespace:
This namespace includes built-in functions,
exceptions, and attributes provided by Python itself.
It's automatically available in all Python scripts.
Python Packages:

• In Python, a package is a way of organizing


related modules into a single directory
hierarchy.
• This allows you to create a collection of
modules that can be easily distributed and
imported by other Python programs.
• Packages are used to structure larger
Python projects, making code organization
and reuse more manageable.
Python Packages:
• The directory that contains the __init__.py file is defined
as a Python package.
• This file can contain initialization code that is executed
when the package is first imported.
• This can include setting up package-level variables,
importing specific modules or subpackages, or
performing any other initialization tasks necessary for
the package to function correctly.
• __init__.py file can be empty.
• A package can be imported the same way as a
module is imported.
Different ways to access Python Packages:

• You can use different Syntax to import Packages


in Python
1. Syntax: import packageName.moduleName
2. Syntax: import
packageName.subPackageName.moduleName
3. Syntax: from packageName import moduleName
4. Syntax: from packageName.subPackageName import
module Name
5. Syntax: from packageName.moduleName import
func_name
6. Syntax: from packageName import*
Python built-in packages:
• Python built-in packages are collections of reusable
modules and functions that extend the capabilities of
Python programming language.
• These built-in packages provide pre-written code to help
developers accomplish common tasks more efficiently.
• Ex:
1. NumPy: NumPy is a powerful library for numerical
computing in Python.
2. Pandas: Pandas is a library for data manipulation and
analysis.
3. Scikit-learn: Scikit-learn is a machine learning library
that provides simple and efficient tools for data mining
and data analysis

You might also like