31/10/2022
Chapter 6
Function
Function
• Python built-in functions: int(), input(), print(), str(), etc
• We can define a function in Python
• Tujuan function:
• Make it easy to develop programs
• Save the number of lines in the source code
• Make it easier for teamwork management to work on projects
• The program becomes more structured/flow, and the program is easy to
understand
• Easier to make documentation
• Reusability -> function can be reused in other programs
1
31/10/2022
How to define a function
How to define a function
2
31/10/2022
Arguments with default value
Dynamic Argument
3
31/10/2022
Non-void Function
• Void Function: a function that only executes the instructions as
defined, no value is returned from the function
• Non-Void Function: a function that executes the instruction as
defined, and there is a value returned from that function. This value
will be used for other calculations.
• Characteristics of non-void function:
• There is a return command inside the function
• The function call is inside an expression
How to define a non-void Function
4
31/10/2022
Calling functions in a library
• A library is a module which contains some functions only
• We can call functions inside of a library, but first we should import
name of the library first
myscript1.py
hello.py or…
“hello” library
myscript2.py
Calling functions in a library
• How if the library resides in a certain directory?
Example:
library hello.py resides in a directory “modules/”
Here is how:
from modules.hello import *
or
import modules.hello
5
31/10/2022
Scope (Local Variable vs Global Variable)
Example 1 Example 3
Example 2
• Local variable is a variable defined in a function
• Global variable is a variable defined in main program (not in a
function)
• Can you identify the different effects of using global vs local
variables from given examples??
Scope (Local Variable vs Global Variable)
Example 4 Example 5
Why a is still 10 not 4 when printed out?
‘global’ is used when we want to set a local var to global var