Subprograms (Functions) in Python: Grade 09 - Topic 02 - Programming and Development Note - Part Iv
Subprograms (Functions) in Python: Grade 09 - Topic 02 - Programming and Development Note - Part Iv
NOTE - PART IV
Built-in subprograms
❖ Built-in subprograms are the subprograms that are given for us to use in our programs.
❖ They are developed by other programmers.
❖ Examples of built-in subprograms we have already used so far:
o print() function : Displays a message as a string.
o input() function : Takes user input as a string.
o int() function : Converts a string value into an integer value.
o float() function : Converts a string value into a float value.
o str() function : Converts a value into a string value.
o range() function : Returns a sequence of numbers starting with 0 by default.
❖ Some subprograms need one or more values written inside their parenthesis to perform the
operation they supposed to perform. Those values are known as argument(s).
❖ Examples:
o print(“Hi”) : To display the string Hi.
o int(“105”) : To convert string 105 to its integer value.
o range(5) : To return 5 numbers starting from 0.
User-defined subprograms
❖ We can create our own subprograms in Python. Such subprograms are known as user-defined
subprograms.
❖ We can create and use one or more user-define subprograms in a single Python program.
❖ For an example, let us create our own subprogram to calculate and return the total of two integers if
we receive the two integers as arguments.
❖ In a Python program, all variables that are created outside subprograms are considered as global
variables.
❖ All variables that are created within a subprogram (including the parameter variables) are considered
as local variables.
❖ So, we have three local variables created in the above example.
o X : Parameter 01.
o Y : Parameter 02.
o Sum : Variable to store the result of the addition.
❖ Local variables are only visible within the subprogram where the variable is created.
o That means in our example, we cannot use or access X, Y or Sum outside the subprogram
addNumbers. Those variables are only visible within the subprogram addNumbers.
❖ To use the subprogram we created, we have to add some more code at the end like shown below: