0% found this document useful (0 votes)
10 views32 pages

ICT01-Course Outcome 6 - Module 4

Uploaded by

Josuel Betonio
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)
10 views32 pages

ICT01-Course Outcome 6 - Module 4

Uploaded by

Josuel Betonio
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
You are on page 1/ 32

Official Business

Functions, Tuples,
Dictionaries, Exceptions,
Data Processing
Official Business

Learning Objectives
By the end of this session, you will be able to:
• Create, use, and call your own functions.
• Learn about parameterless and parameterized functions
• Learn the return expression and the None value.
• Learn about scopes in Python and the global keyword.
• Analyze some multi-parameter functions
• Learn about sequence types and the concept of mutability.
• Learn about tuples and dictionaries.
• Know how to prevent program termination.
• Know tips on testing and debugging codes.
Official Business

Functions
• A function is a block of code
that performs a specific task
when the function is called
(invoked).
• You can use functions to make
your code reusable, better
organized, and more readable.
• Functions can have parameters
and return values.
Official Business

Four Basic Types of


Functions
• Built-in Functions:
These are provided by Python and are available without any
need for importing modules.
Examples: print(), len(), int(), and input().

• Pre-installed Module Functions:


Python also comes with many pre-installed modules, each
containing various useful functions.
Example: the math module has functions like sqrt() and
factorial().
Official Business

Four Basic Types of


Functions
• User-defined Functions:
These are functions created by programmers for specific tasks.
They help in organizing code, making it reusable and
maintainable.

• Lambda Functions:
These are small, anonymous functions defined using the
lambda keyword. They are often used for short, simple
operations, especially when a full function definition is
unnecessary.
Official Business

Defining a Function
• You can define your own function using the def
keyword and the following syntax:

def your_function(optional parameters):


# the body of the function
Official Business

Examples of Defining a
Function
• define a function which doesn't take any arguments

• define a function which takes arguments


Official Business

Parameter Function
• parameters exist only inside functions in which they
have been defined, and the only place where the
parameter can be defined is a space between a pair of
parentheses in the def statement

• assigning a value to the parameter is done at the time of


the function's invocation, by specifying the
corresponding argument.
Official Business

Parameter Function

One Two
Parameter Parameter

Three
Parameters
Official Business
• positional argument passing: the order of arguments passed
matters
Example:

• keyword (named) argument passing: the order of arguments


passed doesn't matter
Example:
Official Business
• a mix of positional and keyword argument passing
Example:

• keyword argument-passing technique: used to pre-define a value


Example:
Official Business

The return Instruction


• It is used inside a function to send the function's result
back to the caller.

• Once a return statement is encountered, the function


terminates, and the specified value or expression is
returned.
Official Business

None in Python
• It is commonly used to signal that a variable has no
value or a function doesn't return anything.
• There are only two kinds of circumstances when None
can be safely used:
− when you assign it to a variable (or return it as a function's
result)
− when you compare it with a variable to diagnose its internal
state.
Official Business

Lists and functions


• List can be passed as an argument to a function. The
function can then operate on the list as needed.
Example:

Results:
Official Business

Functions and Scopes in


Python

• Scope refers to the part of the code where a


variable or function name is accessible.
• Variables defined inside a function are local and
can't be accessed from outside.
• Global variables can be accessed inside functions
unless shadowed by a local variable of the same
name.
Official Business

The global
keyword
• The global keyword allows a
function to modify a variable
that is defined outside of its
local scope, essentially
extending the variable's scope
to include the function.
• Without global, any assignment
inside a function creates a local
variable with the same name,
leaving the global variable
unchanged.
Official Business

Creating multi-parameter
functions
Evaluating the BMI
• BMI(Body Mass Index): Measures body weight in relation to height.
• convert imperial units to metric ones.
Official Business

Creating multi-
parameter functions

• Triangles: Validating
Triangle Sides
-Check if three sides can
form a triangle.
-The sum of any two
sides must be greater
than the third side.
Official Business

Creating multi-parameter functions

• Triangle's area
• Heron's formula:
𝐴=
𝑠 𝑠 − 𝑎 𝑠 − 𝑏 (𝑠 − 𝑐)
𝑎+𝑏+𝑐
wherein 𝑠 =
2

We're going use the


exponentiation operator
to find the square root
Official Business

Creating multi-parameter functions

• Factorials
- 𝑛! = 1×2×⋯×n
- Uses for loop to find the
product
Official Business

Creating multi-parameter
functions

Fibonnaci
• They are a sequence of integer numbers built
using a very simple rule:
• the first element of the sequence is
equal to one
• the second is also equal to one
• every subsequent number is the sum
of the two preceding numbers
Official Business

Recursion
▪ A function that calls
itself.
▪ Cleaner, more elegant
code.
▪ Breaks complex
problems into smaller
parts.
▪ Recursion is powerful
but memory-intensive.
▪ Commonly used in:
• Factorials
• Fibonacci sequence
Official Business

Sequence Types and


Mutability
•Sequence Type: A data type that stores multiple values
that can be iterated sequentially.
Example: Lists, tuples.

•Mutability: Refers to whether data can be modified in


place.
•Mutable: Can be changed (e.g., lists).
•Immutable: Cannot be changed (e.g., tuples).
Official Business

Tuples: Immutable Sequences


•Tuples: An immutable sequence type that uses
parentheses or comma-separated values.
•Tuples can store different data types.
Official Business

Tuple Usage and Restrictions


•Tuples are similar to lists,
but cannot be modified
•Operations:
•len(): Returns the number
of elements in a tuple.
•+: Joins tuples.
•*: Repeats tuples.
•the in and not in operators
work in the same way as in
lists.
Official Business

Dictionaries
•Dictionaries: Mutable, unordered collections of key-value
pairs.
•Keys must be unique and immutable, values can be of
any type.
Official Business

Types of Errors in Python

•Syntax Errors: Occur when Python cannot parse the


code due to incorrect syntax.

•Exceptions: Occur during the execution of syntactically


correct code but cause runtime issues.
Official Business

Handling Exceptions with Try-


Except
•Try-Except Block: Catch and handle exceptions to avoid
program interruption.
•Execution Flow:
1. Try block runs.
2. If an error occurs, jump to the except block.
3. If no error, continue after try-except block.
Official Business

Handling Multiple Exceptions


•You can handle specific exceptions using multiple
except blocks.
Official Business

Multiple Exceptions in One


Clause
•Handle multiple exceptions in a single except block
using parentheses.
Official Business

Common Python Built-in


Exceptions
ZeroDivisionError: Raised when division by zero occurs.
ValueError: Raised when a function receives an argument of the
wrong type.
TypeError: Raised when an operation or function is applied to an
inappropriate type.
AttributeError: Raised when an invalid attribute reference is
made.
KeyboardInterrupt: Raised when the user interrupts program
execution (Ctrl+C).
Official Business

Testing and Debugging


Debugging Tips:
• Use print statements to trace variables and
logic.
• Ask others to review your code.
• Isolate problematic code fragments for
testing.
• Take breaks to approach problems with fresh
eyes.

You might also like