PROGRAMMING
SCIENTIFIC
SKEE1033
FUNCTIONS
( WEEK 5 )
DR. AHMAD SHAHIDAN ABDULLAH
DR. AHMAD SHARMI ABDULLAH
DR. AMIRJAN NAWABJAN
DR. MOHD ADIB SARIJARI
DR. MUHAMMAD AL FARABI MUHAMMAD IQBAL
DR. MUHAMMAD ARIFF BAHARUDIN
PM. IR. TS. DR. ASRUL IZAM AZMI
PM. IR. TS. DR. MICHAEL TAN LOONG PENG
OBJECTIVES
• Create Function
1) Define functions with single/multiple inputs and outputs.
2) Use local functions and nested functions.
• Variable scope
1) Differentiate between global and local scopes..
2) Understand variable scope in scripts, main, and nested functions.
• Libraries
1) Learn about Python libraries and how to use them (import).
SKEE 1033 2
OPERATION (RECAP)
STATEMENT FUNCTION
1. ASSIGNMENT Group of statement
syntax
that perform a task
Assign array to a variable using syntax
EQUAL OPERATOR def function_name(input1, input2):
variable = expression # Code block
return output
2. REPITITION Arithmetic
TYPE
Execute statements specified Boolean
number of times using
while COMMAND
BOOLEAN OPERATOR
or ITERATION PROTOCOL for
Direct instructions
often used in the
syntax command line
3. DECISION
Execute statements if if REPL: Read-Eval-Print Loop, which
condition is TRUE using if-else is an interactive programming
if-elif-else environment that takes single user
BOOLEAN OPERATOR
inputs (commands), evaluates them,
and returns the result to the user.
SKEE 1033
3
WHAT IS FUNCTION
• Program file
A .py file that contains Python code
Types of program file:
1) Script file – contains sequences of commands, function calls, and
can include local function
2) Function file – contains only function definitions.
• What is function?
A block of code that accepts inputs and returns outputs.
• Why use function?
Cleaner code
Maintainability
Reuse
Hiding implementation
SKEE 1033 4
FUNCTION VS SCRIPT
Aspect Script Function
Usage Both allow reuse of code sequences in .py files.
Program Fixed variables. A more flexible and easily
extensible program
Input/output No direct input/output Accepts inputs and returns
handling. outputs.
Workspace Global scope, affects and Local scope, variables are
accesses global variables. contained within the
function.
SKEE 1033 5
TYPES OF FUNCTION
• Predefined Python function.
Built-in functions: Predefined and directly accessible (e.g., print(), len()).
Library functions: Provided by libraries (e.g., numpy, pandas), accessible
through imports
• User defined function:
Standard functions: Defined using def, accessible by name.
Local functions: Defined inside another function, accessible only within it.
Lambda (Anonymous) functions: Short, unnamed functions defined with
lambda.
Private functions: Conventionally marked with an underscore intended for
internal use.
SKEE 1033 6
PRE-DEFINED PYTHON FUNCTION
BUILT-IN FUNCTIONS
Example 1: Built-in Functions
Description: Predefined functions available without any imports.
Examples: print(), len(), max()
Syntax:
# 1. print() - Prints output to the console
print("Hello, World!") # Output: Hello, World!
# 2. len() - Returns the length of an iterable (e.g., list, string)
length = len([1, 2, 3])
print("Length:", length) # Output: 3
# 3. max() - Returns the maximum value among the given arguments
max_value = max(10, 20, 30)
print("Max Value:", max_value) # Output: 30
# 4. abs() - Returns the absolute value of a number
absolute_value = abs(-7)
print("Absolute Value:", absolute_value) # Output: 7
# 5. sum() - Returns the sum of all items in an iterable
total = sum([1, 2, 3, 4])
print("Sum:", total) # Output: 10
SKEE1033 8
LIBRARY FUNCTIONS
Example 2: Library Functions
Description: Functions available through importing Python libraries
Examples: Functions from numpy, pandas, etc.
Syntax:
import math
# 1. [Link]() - Computes the square root of a number
result = [Link](16) # Output: 4.0
print("Square Root:", result)
import numpy as np
# 2. [Link]() - Creates a numpy array
array = [Link]([1, 2, 3]) # Creates a numpy array
print("Numpy Array:", array) import pandas as pd
# 3. [Link]() - Creates a pandas Series
series = [Link]([10, 20, 30], index=['a', 'b', 'c'])
print("Pandas Series:\n", series) import random
# 4. [Link]() - Selects a random element from a list
choices = ['apple', 'banana', 'cherry’]
random_choice = [Link](choices) # Randomly selects one item from the list
print("Random Choice:", random_choice)
SKEE1033 9
USER DEFINED FUNCTION
Understanding def in Python
• What is def?
def is a keyword in Python used to define a function.
Functions are reusable blocks of code that perform a specific
task.
Functions help in organizing code, making it more readable and
maintainable.
11
Understanding def in Python
• How to Write a Function using def:
Define the function: Use the def keyword followed by the
function name and parentheses ().
Add Parameters (optional): List any input parameters inside the
parentheses.
Add a Colon : ndicate the start of the function body.
Write the Function Body: Indent the code inside the function.
Return (optional): Use return to send back a result from the
function.
# Defining a simple function
def greet(name): # 'name' is the parameter
print(f"Hello, {name}!") # Function body with an indented block
# Calling the function
greet("Alice") # Output: Hello, Alice!
12
Standard Function (Single Input, Single Output)
• Example 3: A standard function defined using def that takes one
input and returns one output.
def square(number):
return number ** 2
print(square(4)) # Output: 16
16
13
Standard Function (Single Input, Multiple Output)
• Example 4: A standard function that takes one input and returns
multiple outputs.
def analyze_number(num):
is_even = num % 2 == 0
square = num ** 2
return is_even, square
even, sq = analyze_number(5)
print("Is Even:", even, "Square:", sq)
# Output: Is Even: False Square: 25
Is Even: False Square: 25
14
Standard Function (Multiple Input, Single Output)
• Example 5: A standard function that takes multiple inputs and
returns one output.
def add(a, b):
return a + b
print(add(3, 7)) # Output: 10
10
15
Standard Function
(Multiple Input, Multiple Output)
• Example 6: A standard function that takes multiple inputs and
returns multiple outputs.
def calculate(a, b):
addition = a + b
subtraction = a - b
multiplication = a * b
division = a / b if b != 0 else None
return addition, subtraction, multiplication, division
add_result, sub_result, mul_result, div_result = calculate(8, 2)
print("Addition:", add_result, "Subtraction:", sub_result,
"Multiplication:", mul_result, "Division:", div_result)
Addition: 10 Subtraction: 6 Multiplication: 16 Division: 4.0
16
Local Function
• Example 7: Applying discounts with local function
def process_order(quantity, price_per_item):
# Local function to calculate total price with a discount
def calculate_total(qty, price):
total = qty * price
if total > 100: # Apply a discount if total is over 100
return total * 0.9 # 10% discount
return total
total_price = calculate_total(quantity, price_per_item)
return f"Total Price: ${total_price:.2f}"
# Testing the local helper function
print(process_order(10, 15)) # Output: Total Price: $135.00 (with discount)
Total Price: $135.00
• calculate_totalis defined inside process_order, making it a local
function that can only be accessed within process_order.
17
Multiple Local Functions
• Example 8: Applying discounts and taxes with local functions
def process_order(quantity, price_per_item):
# Two Local function to calculate total price with a discount and tax
def calculate_total(qty, price):
total = qty * price
if total > 100:
return total * 0.9 # Apply 10% discount
return total
def apply_tax(amount, tax_rate=0.05): # Apply 5% tax
return amount * (1 + tax_rate)
total_price = apply_tax(calculate_total(quantity, price_per_item))
return f"Total Price after tax: {total_price}"
# Test the function
print(process_order(10, 15)) # Output: Total Price after tax: 141.75
Total Price after tax: 141.75
• and apply_tax are defined inside process_order, making
calculate_total
them local functions that can only be accessed within process_order.
18
Lambda (Anonymous) Functions
• Example 9: Short, unnamed functions defined with lambda.
square = lambda x: x ** 2
print(square(4)) # Output: 16
16
19
Private Functions
• Example 10: Conventionally marked with an underscore, intended
for internal use.
• When _private_function() is defined, it is treated like any other
function, but the underscore signals it’s meant for internal use.
• It can still be called normally, as shown, printing the message
def _private_function():
print("This is a private function.")
_private_function() # Output: This is a private function.
This is a private function.
20
Function with No Input/Output
• Example 11: Performs a task but does not take any inputs and
does not return any values.
• These functions are useful when you need to perform an action (like
logging, printing, or updating something) without needing any input
or generating a specific output.
# Function with no input and no output
def greet():
print("Hello, World!") # Prints a message to the console
# Calling the function
greet() # Output: Hello, World!
Hello, World!
21
Add Help Documentation to Python Functions
• Example 12: Add Help Documentation in Python:
• Use a Docstring: Add a triple-quoted string """ ... """ right after the
function definition.
• Access the Help: Use help(function_name) or
function_name.__doc__ to view the documentation.
def calculate_circle_area(radius):
"""
Calculate the area of a circle given its radius.
Parameters: radius (float): The radius of the circle.
Returns:
float: The area of the circle.
"""
return [Link] * radius ** 2
# Accessing help
help(calculate_circle_area)
22
Selective Output Handling
• Example 13: You can choose to unpack only the required outputs
by indexing or unpacking the returned values.
• motion(t)[0] accesses the first item in the returned tuple, which is
jarak.
# Define a function that returns multiple outputs
def motion(t):
# Example calculations for demonstration
jarak = [0.0001 * i ** 2 for i in t] # Simulated distance values
pecutan = [0.0025 * i ** 2 for i in t] # Simulated velocity values
return jarak, pecutan
# Calling the function with t as input
t = [0, 0.1, 0.2, 0.3, 0.4, 0.5]
# Case 1: Requesting only the first output
jarak = motion(t)[0] # Getting only the first output
print("Jarak:", jarak) # Output: Jarak: [0.0, 1e-06, 4e-06, 9e-06, 1.6e-05, 2.5e-05]
Jarak: [0.0, 1.0000000000000002e-06, 4.000000000000001e-06, 9e-06, 1.6000000000000003e-05,
2.5e-05]
23
Selective Output Handling
• Example 13 (continued):
# Case 2: Requesting both outputs
jarak, pecutan = motion(t) # Unpacking both outputs
print("Jarak:", jarak) # Output: Jarak: [0.0, 1e-06, 4e-06, 9e-06, 1.6e-05, 2.5e-05]
print("Pecutan:", pecutan) # Output: Pecutan: [0.0, 2.5e-06, 1e-05, 2.25e-05, 4e-05,
6.25e-05]
Jarak: [0.0, 1.0000000000000002e-06, 4.000000000000001e-06, 9e-06, 1.6000000000000003e-05,
2.5e-05]
Pecutan: [0.0, 2.5000000000000005e-05, 0.00010000000000000002, 0.000225,
0.0004000000000000001, 0.000625]
24
USING FUNCTIONS FROM
EXTERNAL FILES IN PYTHON
Python Modules
• In Python, functions can be organized into separate files, known as
modules, and can be called from other scripts or files.
• Modules help organize code into reusable and manageable parts,
making it easier to maintain and understand.
• Key Features of Modules
• Organize Code: Group related code into separate files.
• Reusability: Use the same code across multiple projects without
duplication.
• Avoid Naming Conflicts: Each module has its own namespace.
26
Create and Use a Module
• Example 14 : How to Create and Use a Module
1. Creating a Module: math_operations.py:
a) Save your code in a .py file with a descriptive name. This file is your
module.
b) Save your functions in a file, e.g., math_operations.py:
# math_operations.py - This is your module
# This module defines basic mathematical operations.
def add(a, b):
# Returns the sum of two numbers.
return a + b
def subtract(a, b):
# Returns the difference between two numbers.
return a - b
27
Create and Use a Module
• Example 14 (continued):
2. Using the Module in Another File: main_script.py
a) Import and use functions in another script, main_script.py:
# main_script.py
# This script demonstrates using functions from the math_operations module
# Import the entire math_operations module
import math_operations
# Using functions from the imported module
print(math_operations.add(10, 5)) # Output: 15
print(math_operations.subtract(10, 5)) # Output: 5
Reloaded modules: math_operations
15
5
28
Create and Use a Module
• Example 14 (continued):
3. Using the Module in Another File: use_add.py
a) You can import only the needed functions from the module using from
... import ... syntax.
# use_add.py
# This script imports and uses the add function specifically from math_operations.
# Import only the add function from the module
from math_operations import add
# Using the imported add function
print(add(7, 3)) # Output: 10
Reloaded modules: math_operations
10
29
Purpose of the main() Function in Python
What is main() ?
• A function that contains the main code logic of a script.
• Used with if __name__ == "__main__": main() to control when
the main code runs.
Why Use main() ?
• Organizes Code: Separates main logic from function definitions,
making the script cleaner.
• Enables Reusability: Functions can be imported into other scripts
without running the example code in main()
• Controls Execution: Ensures main() only runs when the script is
executed directly, not when imported as a module.
30
main() Function with another Function in a Script
• Example 15: main() Function with another Function in a Script
import numpy as np
def celsius_to_fahrenheit(celsius_array):
return (celsius_array * 9/5) + 32
def main():
# Generate an array of Celsius temperatures from -20 to 100 with 10 values
celsius_array = [Link](-20, 100, 10)
# Convert to Fahrenheit fahrenheit_array =
celsius_to_fahrenheit(celsius_array)
# Print the result using f-strings
print(f"Celsius temperatures: {celsius_array}")
print(f"Fahrenheit temperatures: {fahrenheit_array}")
# Only execute the main function if the script is run directly
if __name__ == "__main__": main()
31
main() Function with another Function in a Script
• Example 15 (continued)
1. By putting the primary code in main():, the celsius_to_fahrenheit
function becomes reusable.
2. When this script is imported into another script, only the
celsius_to_fahrenheit function will be accessible, and the code in
main() won’t run. This prevents unintended execution of test code or
examples when you just want to use the conversion function.
3. Checking __name__ == "__main__": main()
● The condition if __name__ == "__main__": main() checks whether
the script is being run directly or being imported.
● If the script is run directly, this condition is True, so main() is
executed.
● If the script is imported, this condition is False, so main() is not
executed.
32
VARIABLE SCOPE
VARIABLE SCOPES IN PYTHON
In Python, understanding variable scopes is crucial for managing how variables are
accessed and modified within different parts of your code.
Scopes help protect data integrity and ensure that variables are only accessible
where they are intended to be used. Python has four main scopes:
1. Global Scope (Base Workspace)
a. Variables defined at the top level of a script or module.
b. Accessible throughout the script, including within functions (unless shadowed).
c. Used for defining variables that need to be accessed globally.
2. Local Scope (Function Workspace)
a. Variables defined inside a function.
b. Accessible only within that function.
c. Keeps function data isolated, ensuring variables do not interfere with other
functions.
SKEE 1033 34
VARIABLE SCOPES IN PYTHON
3. Enclosed Scope (Nested Functions)
a. Variables defined in a function that is inside another function.
b. Accessible to the inner function but not to other parts of the script or outer global
scope.
c. Useful for encapsulating helper functions.
4. Built-in Scope
a. Contains Python’s built-in functions and variables (e.g., print, len).
b. Accessible throughout all scopes without being explicitly defined.
SKEE 1033 35
SCOPE
Main Program File
(Script File)
A B
Modules
Top-Level
Function Top-Level
Function
A
Nested
Function
A Nested
Function
A B
AB
Base variables Local variables
SKEE 1033 36
LIBRARIES
EXPLORING PYTHON LIBRARIES AND THEIR
USAGE
What Are Python Libraries?
• Definition: Collections of pre-written code that provide ready-to-use
functions, modules, and tools to speed up development.
• Purpose: Simplify complex tasks, promote code reuse, and save
development time
SKEE 1033 38
EXPLORING PYTHON LIBRARIES AND THEIR
USAGE
Popular and Useful Python Libraries
• Data Analysis:
• Pandas: For data manipulation and analysis.
• Example: Handling data frames and performing statistical operations.
• Machine Learning & AI:
• Scikit-Learn: Provides simple and efficient tools for data mining and
machine learning.
• TensorFlow: For deep learning and neural network building.
• Web Development:
• Flask: A lightweight web framework for building web applications quickly.
• Django: A high-level framework that encourages rapid development and
clean, pragmatic design.
SKEE 1033 39
EXPLORING PYTHON LIBRARIES AND THEIR
USAGE
Popular and Useful Python Libraries (continued)
• Data Visualization:
• Matplotlib: For plotting data with 2D graphs.
• Seaborn: Built on top of Matplotlib, it offers enhanced statistical graphics.
• Scientific Computing:
• SciPy: Used for scientific and technical computing.
• NumPy: Supports large, multi-dimensional arrays and matrices.
SKEE 1033 40
SEARCH FOR NEW PYTHON LIBRARIES
Popular Website
• PyPI (Python Package Index)
• Website: [Link]
• What it is: The official repository for Python libraries. It hosts thousands of
packages that are easily searchable.
• GitHub
• Website: [Link]
• What it is: A platform for hosting code repositories. Many Python libraries
are developed and shared on GitHub.
• Awesome Python
• Website: [Link]
• What it is: A curated list of awesome Python frameworks, libraries,
software, and resources.
SKEE 1033 41