Py Week 06 1
Py Week 06 1
ෙනාහැක්කක් ෙනාමැත
www.heladevs.org
Where we are ??
Functions
What is Part 2 -
Intro
Computing Advanced
Programming concepts
Languages
Variables &
Data Types
Flow Control
Flow Control
Continuation
Loops
Functions
week-01 week-14
Previous This Week
Week
Python type system
● Statements
● What is a function
● While loop ● Types of functions
● for loop
● Function
● break statement
declaration
● continue statement
● Nested loops
● Calling functions
● Arguments
● Return of a
function
● Benefits of using
functions
What is a Function?
• A function is a block of organized, reusable code that is used to perform a
single, related action
• In other words, function can be treated as a subprogram, a small program
within a much larger program
• It is a sequence of statements which has a name. We can execute this
sequence at any given time by referring to this name
• Functions can also take one or more inputs and process them and produce
one or more outputs
• Functions provides better modularity for your application and a high degree
of code reusing
• They also increase the code readability
Real world Examples
• Displaying data
• Validating user inputs
• A calculation on a set of numbers (ie. average, max, min, std.dev)
• Conversion of units
• Send an email
• Performing a file operation
Functions vs Methods
• A method also refers to a
function which is a part of a
class
• We need an instance or object
of that class to call or use a
method
• But a function is not attached
to a particular class.
• Python classes, instances,
methods will be covered in a
separate session
Types of Functions
There are two types of functions in python.
https://docs.python.org/3/library/functions.html
Python Function Declaration
• Function begins with “def” keyword followed by the name of the
function and parentheses – ()
• Next, we can define the parameters (inputs) as per the requirements
within these parentheses. This is optional
• Next, the colon indicates the end of the python function header (the
name and parameter list)
• The body of statements can contain a block of valid python code
• The return expression exits a function. This is also optional like input
parameters. But it is very useful when we want to pass back an
expression to the caller or return an output to the calling code
Python Function Declaration
Naming a Function
• Function names should use only letters, numbers, and underscores _
• Function names should not start with digits
• Function names should not use spaces or other special characters.
• If the function name consists of multiple words, it should use the snake_case
convention, which means using underscores (_) to separate words.
• Function names should follow the PEP 8 style guide.
Week 14
Week 08
• Functions part 2
Week 07 (Advanced
• Functions concepts)
ෙනාහැක්කක් ෙනාමැත