0% found this document useful (0 votes)
7 views48 pages

Lesson 06 Python Functions

This document provides a refresher on Python functions, covering their definition, advantages, syntax, and types, including built-in and user-defined functions. It explains the use of arguments, variable scope, and introduces generators and lambda functions. The document emphasizes the importance of functions for creating modular and reusable code in programming.
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)
7 views48 pages

Lesson 06 Python Functions

This document provides a refresher on Python functions, covering their definition, advantages, syntax, and types, including built-in and user-defined functions. It explains the use of arguments, variable scope, and introduces generators and lambda functions. The document emphasizes the importance of functions for creating modular and reusable code in programming.
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

Programming Refresher

Python Functions
Learning Objectives

By the end of this lesson, you will be able to:

Illustrate the concept of functions

Summarize the advantages of functions

Design a function with arguments

Explicate the scope of a variable in a function

Summarize generators
Business Scenario

ABC is a Fintech company that deals with onboarding merchants for its payment
gateway. For every new merchant added, there is a new class created in the
backend, and the code is customized based on the merchant's requirement.
However, when the code is analyzed, they notice that it has a separate code every
time for each merchant module, which is not efficient and is time-consuming.

This can be solved by combining repetitive tasks and writing them inside a
function so that the same part of the code can be called anywhere in the code
stack for any merchant.

To do so, the organization will explore functions, variables, and their scope, which
will help complete the task.
Functions and Its Advantages
Discussion
Python: Functions

Are functions and loops the same?

• What are functions in Python?


• Why are they useful?
Python: Functions

• A function is a collection of connected


statements that achieves a certain goal.
• It may be defined as an organized block of
reusable code.
• It is a code block that only executes when it is
invoked.
• Parameters are data that are passed into a
function.
Functions: Advantages

The advantages of functions are:

1 Reusability

Enables the 2
comprehensibility
3 Modularity
Enhances the quality of the 4
program
5 Scalability

6
Ease of use
Functions: Syntax

The basic syntax of a function in Python consists of two parts:

Function definition
• A function is defined using the keyword def followed by a function name and
01
parenthesis.
• The argument names passed to the function are mentioned inside this parenthesis.
• The body of the function is an indented block of code.

Syntax

def myFunction(arg1, arg2):


body
Functions: Syntax

The basic syntax of a function in Python consists of two parts:

Function call
• A function can be called from anywhere in the program in order to be used.
02 • When a function is called, the program control is transferred to the called function
to perform the defined task.
• All the necessary parameters and arguments should be passed during the function
call.

Syntax

myFunction(arg1, arg2)
Python: Functions

Are functions and loops the same?

• What are functions in Python?


Answer: A function is a collection of connected statements that achieves a
certain goal.

• Why are functions required?


Answer: Functions enhance the comprehensibility, quality scalability,
modularity, and reusability of the program.
Function Arguments
Functions: Arguments

The features of the arguments are mentioned below:

Information can be passed to A function may have zero to


a function in the form of multiple arguments
arguments. separated by a comma.
Plan
Features

The arguments are specified and


enclosed in parentheses in the The arguments can be data values,
function definition immediately objects, or functions.
after the function name.
Functions: Argument Matching

Arguments in Python can be matched by position or name.

Positional arguments are Keyword arguments are


required to be mentioned in referenced by name and may
the same order as in the be in any order.
function definition.

Positional and keyword arguments can be mixed


in a function call.
Note

Arguments in a function may also be defined with a default value.


Assisted Practice: Function and Argument Matching

Duration: 5 mins

Objective: In this demonstration, you will learn to create a function with arguments.
Steps to perform:
Step 1: Create a function
Step 2: Pass arguments to the function
Step 3: Perform argument matching
Step 4: Call the function and display the results
Functions: Arbitrary Arguments

Python allows the passing of variables with multiple arguments by using special
symbols.

Symbols used for passing arguments

*args **kwargs
Non-keyword arguments Keyword arguments

Note

These notations are used when the number of arguments to be passed to the function is uncertain.
Functions: Arbitrary Arguments

The types of arbitrary arguments are explained below:

Non-keyword arguments Keyword arguments

Keyword arguments are defined using **.


The symbol * is used to take in a variable number
Conventionally, “kwargs” is used to define the
of arguments.
keyword arguments.

Conventionally, “args” is used to define the non- A keyword argument allows giving the variable a
keyword argument. name before passing it to the function.

Keyword arguments are like a dictionary where


These arguments are unpacked as a list inside the
each value is mapped to the keyword passed along
function.
with it.
Assisted Practice: Arbitrary Arguments

Duration: 5 mins

Objective: In this demonstration, you will learn to use arbitrary arguments.


Steps to perform:
Step 1: Define a function that takes arbitrary arguments
Step 2: Pass arguments to the function
Step 3: Call the function and display the results
return Statement
Functions: return Statement

The return keyword is used to pass values back to the function call.

If the return statement is not After the return statement is


used, Python returns None executed, no further statements
by default. of the function are executed.

A function can return none to


multiple values or data objects.
Assisted Practice: return Statement

Duration: 5 mins

Objective: In this demonstration, you will learn to use the return statement.
Steps to perform:
Step 1: Define a function with arguments
Step 2: Use the return statement to return values when the function is called
Step 3: Call the function and display the results
Scope of a Variable
Function: Scope

Scope in programming defines the environment where the variables can be


accessed and referenced.

If a value of a variable is to
be retrieved in a function,
It defines the functional
Features it searches for the global
range of any variable or
environment of each
function.
package on the search list.
Function: Scope

There are two types of scope:

Global scope Local scope

Variables and functions defined outside Variables or functions that are defined
of all classes and functions have global inside a function block including
scope. argument names, are local variables.

It allows the variable values to be used


It can be accessed only inside the
or functions to be called from anywhere
function block.
in the file in the program.
Generators Function
Function: Generators

Generators are a special type of function supported in Python that returns an iterator
object with a sequence of values.

A generator uses a yield statement instead of a return statement.

A generator object can be iterated only once.


Features

A function with a yield statement is termed a generator.


return vs. yield Statement

The difference between the return and yield statements are given below:

return statement yield statement

• The return statement implies that • The yield statement implies that
the function is returning control of the transfer of control is
execution to the point from where temporary.
the function is called.
• Hence, it does not destroy the
• The process destroys the local states of the function’s local
variable and values generated. variables.
Generator: Example

Here a generator function is defined that yields three values:

Note

In place of multiple yield statements, a loop can also be used inside the function to
generate the values.
Ways to Use a Generator

The generator function can be used in two ways :

It can be used with the built-in next It can be used with a for loop as an
function. iteration object.
Lambda Functions
Lambda Functions

Python lambda functions are anonymous functions and can be defined by using the keyword lambda.

A lambda function may have any number of arguments but contains only one
expression.

The lambda functions are syntactically restricted to only a single expression


which is evaluated and returned.
Features

It is possible to define a lambda function without assigning it to a variable or


explicitly calling it.

Syntax: lambda arguments: expression


Function Types
Types of Functions

Functions can be of two types:

Built-in functions User-defined functions

Built–in functions are predefined Python also supports the creation of


functions in the programming customized user-defined functions to
framework. perform specific tasks.

Python has basic built-in functions, such


A user can give any function name with
as len(), sum(), type(), slice(), next(), help(),
any number of arguments.
format().
Functional Programming Implementation
Functional Programming Methods

These built-in functions facilitate functional programming in Python, which uses


methods to define computation.

Filter function
Syntax: filter(func, iterable)

Map function Reduce function


Types
Syntax: map(func, iterable) Syntax: reduce(func, iterable)

The map and filter functions are basic built-in functions, whereas the
reduce function is a part of a module named “_functools.”
map()

A map function can be used to apply a function to each element of


an iteration object.

Example
• The map function takes in two
arguments a function and an iterable
object.
• It applies the given function to all
elements of the given iteration object.
• It generates an iterator which can be
converted to a list.
• It can also use the lambda function for
implementation.
filter()

A filter function is used to filter data based on a condition


defined in a function.

Example

• The filter function also takes a function and


an iterable object and applies the function to
each element of the iteration object.
• The given function should return a Boolean
value.
reduce()

A reduce function is used to implement the mathematical technique of


folding on an iteration object.

Example
• The reduce function takes in a function an
iterable object.
• The reduce function applies the function
continually to each element of the iterable
object and produces a single cumulative value.
Key Takeaways

Functions are an important structure of any programming language


to create a modular and reusable application.

Python functions use the def keyword to define functions, can take
0 or more arguments, and can return a value or None.

Variables declared in the function have local scope and


variables declared outside a function have global scope.

Iterators are a way to traverse over a string, list, or tuple and they
exhibit the concept of generators.

The Lambda keyword is used to define an anonymous function in


Python.
Knowledge Check
Knowledge
Check
The advantages of functions are:​
1

A. Reusability​

B. Ease of use​

C. Scalability​

D. All of the above​


Knowledge
Check
The advantages of functions are:​
1

A. Reusability

B. Ease of use​

C. Scalability​

D. All of the above​

The correct answer is D

Functions can be reused, easy to access, and scalable.​


Knowledge
Check
Information can be passed to a function in the form of _______.​
2

A. Arguments

B. Names

C. Tasks

D. All of the above


Knowledge
Check
Information can be passed to a function in the form of _______.​
2

A. Arguments​

B. Names

C. Tasks

D. All of the above​

The correct answer is A

Information can be passed to a function in the form of arguments or parameters.​


Knowledge
Check
A function is defined using the keyword _____.​
3

A. func

B. function

C. def​

D. All of the above​


Knowledge
Check
A function is defined using the keyword _____.​
3

A. func

B. function​

C. def

D. All of the above​

The correct answer is C

A function is defined using the keyword def followed by a function name and parenthesis.​
Thank You

You might also like