PYTHON FUNCTIONS
Reusing Code for Efficiency
Camille Joy Sosa
Python Functions
A function is a block of reusable code that performs a specific task or set of
tasks. Functions allow you to organize your code into manageable and
modular pieces, making it easier to understand, maintain, and reuse.
There are two kinds of functions in Python.
1. Built-in functions.
2. User-defined Functions.
Note: We treat function names as “new” reserved words
(i.e., we avoid them as variable names)
Python Functions
A function is a block of reusable code that performs a specific task or set of
tasks. Functions allow you to organize your code into manageable and
modular pieces, making it easier to understand, maintain, and reuse.
There are two kinds of functions in Python.
1. Built-in functions.
2. User-defined Functions.
Note: We treat function names as “new” reserved words
(i.e., we avoid them as variable names)
Built-in Functions
Built-in functions are those that are provided by Python as part of its standard
library. These functions are readily available for use without the need for
explicit definition.
Built-in Functions
Built-in functions are those that are provided by Python as part of its standard
library. These functions are readily available for use without the need for
explicit definition.
Call Function
We call/invoke the function by using the function name, parentheses, and
arguments in an expression
User-defined Functions
User-defined functions are created by the programmer to perform a specific
task or set of tasks. They allow the programmer to modularize their code,
making it more organized, readable, and reusable.
Syntax of defining a function in Python
In Python, you can define a function using the def keyword followed by the
function name, parentheses (), and a colon : to indicate the start of the
function block.
Syntax of defining a function in Python
1. The def keyword marks the beginning of a function definition.
2. The function_name is the identifier for the function, following Python's naming
conventions.
3. Parameters, enclosed in parentheses, allow passing data into the function for
processing.
4. The colon : signifies the start of the function block, enhancing syntax clarity.
5. The function body contains the code defining the functionality, executing when
the function is called.
6. The return statement, optional, exits the function and optionally returns a value
to the caller; if omitted, the function implicitly returns None.
Simple Function
This code defines a function called `subject()` which, when called, prints the
message "CpE 401 Computer Programming I", essentially providing
information about a course.
Scope of variables:
Global variables are accessible throughout the entire program, while Local
variables are confined to the block of code (such as a function) where they
are defined.
Function with parameter
In this version, the subject() function takes one parameter course, and when
called with an argument, it prints "Course:" followed by the value of the
course parameter.
Function with multiple parameters
This function student_profile takes three parameters: name, age, and
program. Inside the function, it prints out the information provided for each
parameter.
When you call the function with student_profile("Xavier", 20, "Mechanical
Engineering"), it passes "Xavier" as the name, 20 as the age, and "Mechanical
Engineering" as the program.
Function with return value
The return statement ends the function execution and “sends back” the result
of the function
Reusable Function
The `square` function calculates the square of a given number, promoting
code reuse by encapsulating the square calculation logic, allowing it to be
easily applied to different input values within the program.
Applying Functions in Selection Statements:
The `is_even` function, utilized within the selection statement, determines
whether the inputted number is even or odd, directing the program flow
accordingly.
Applying Functions in Loops:
This function `square_numbers` takes a list of numbers as input, squares each
number using a loop, and returns a new list containing the squared numbers.
Error Handling
"try" and "except" are keywords in Python used for error handling,
particularly in situations where you anticipate that certain code might cause
an error.
• try:
The "try" block contains the code that you want to execute. You put the
code that might raise an exception inside this block.
• except:
The "except" block is where you handle the exception if it occurs. If
any exception occurs in the "try" block, Python looks for an "except" block
that matches the type of exception raised.
Error Handling
ExceptionType: This can be a specific type of exception that you expect might
occur, such as TypeError, ValueError, or IOError. You can also use a general
Exception to catch any type of exception.
Handling the Exception: Inside the "except" block, you write code to handle
the exception. This could involve logging the error, providing a user-friendly
message, or attempting to recover from the error.
ZeroDivisionError exception
ZeroDivisionError: Raised when division or modulo by zero is encountered.
Dividing any number by zero is not possible in mathematics, hence Python
raises this error to indicate that the operation is invalid.
ValueError
ValueError: Raised when a built-in operation or function receives an
argument that has the right type but an inappropriate value. The int()
function expects a string representing an integer, but when it receives a string
that cannot be converted to an integer, it raises a ValueError.
IndexError
IndexError: This error occurs when you try to access an index that is outside
the bounds of a sequence (e.g., list, tuple, string). In Python, indexing starts
from 0, so my_list[4] tries to access the fifth element of my_list, which
doesn't exist, resulting in an IndexError.
TypeError
TypeError: Raised when an operation or function is applied to an object of
inappropriate type. Adding a string (y) to an integer (x) is not supported in
Python, hence it raises a TypeError indicating that the operation is not valid
for the given types.
KeyError
KeyError: Raised when a dictionary key is not found. "c" is not a key in
my_dict. Attempting to access it using my_dict["c"] raises a KeyError because
the key does not exist in the dictionary.
THANK YOU