Python Lesson 4b Notes - Updated 1
Python Lesson 4b Notes - Updated 1
1 of 38
Contents
Functions in Python
A function is a block of organized and reusable code that can perform a single,
related action. Functions provide better modularity for the program and a higher
degree of code reusing.
As you already know, Python gives you many built-in functions like print(), range()…
etc. We, instead, can also create our own functions. These functions are
called user-defined functions.
Define Function
Follow the guidelines below to set definitions of the functions.
➢ Function blocks begin with the keyword def followed by the function name
and parentheses ( ).
➢ The code block within every function starts with a colon : and is indented.
# oddEven.py
# A simple Python function to check
# whether x is odd or even
Elaboration of oddEven.py
1. Function Definition
def oddEven(x):
2. Conditional Logic
if (x % 2 == 0):
print("%d is even number!" % x)
else:
print("%d is odd number!" % x)
➢ Purpose: The function uses an if-else statement to check the parity of the
number x.
➢ Explanation:
✓ x % 2 == 0:
If the remainder when x is divided by 2 is 0, the number is
even.
✓ else:
If the condition x % 2 == 0 is False, the number is odd.
➢ String Formatting:
✓ The %d placeholder is used to insert the value of x into the printed
string.
P. 5 of 38
➢ First Call:
oddEven(18)
➢ Second Call:
oddEven(19)
➢ This line prints a message to indicate that the oddEven function will be
invoked twice.
➢ The use of escape characters (\") allows quotation marks to appear in the
output string.
P. 6 of 38
On the other hand, you may also write the function with return statement. Try the
following code listing named oddEvenWithReturn.py, it generates the same result as
the previous program oddEven.py.
# oddEvenWithReturn.py
# A simple Python function to check
# whether x is odd or even
result = oddEven(18)
print("18 is %s number!" %result)
result = oddEven(19)
print("19 is %s number!" %result)
Elaboration of oddEvenWithReturn.py
1. Function Definition
def oddEven(x):
if (x % 2 == 0):
return "even"
else:
return "odd"
➢ This line prints a message indicating that the oddEven function will be
invoked twice.
➢ The use of escape characters (\") allows quotation marks to appear in the
output.
P. 8 of 38
➢ Function Call:
result = oddEven(18)
➢ Output Statement:
print("18 is %s number!" % result)
➢ Function Call:
result = oddEven(19)
➢ Output Statement:
print("19 is %s number!" % result)
oddEvenWithReturn - by variable.py
# oddEvenWithReturn.py
# A simple Python function to check
# whether x is odd or even
ch = input('')
P. 10 of 38
➢ This line prints a message indicating that the oddEven function will be
invoked twice.
➢ The use of escape characters (\") allows quotation marks to appear in the
output.
P. 11 of 38
➢ Variable Assignment:
k = 18
➢ Function Call:
result = oddEven(k)
➢ Output Statement:
print("%d is %s number!" % (k, result))
➢ Function Call:
result = oddEven(19)
➢ Output Statement:
print("19 is %s number!" % result)
Classwork 1
Try to write a Python Program (factorialFunc.py) that can calculate the factorial of an
integer. In Mathematics, the factorial of a non-negative integer n, denoted by n!, is
the product of all positive integers less than or equal to n.
Please refer to the following figures for reference before writing the Python program,
factorialFunc.py:
Figure 1
P. 14 of 38
Figure 2
P. 15 of 38
Keyword Arguments
When using keyword arguments in a function call, the caller identifies the arguments
by the parameter name.
This will allow the skipping of arguments or placing them out of order because the
Python interpreter is able to use the keywords provided to match the values with
parameters.
#keywordFunc.py
ch = input('')
P. 16 of 38
Elaboration of keywordFunc.py
1. Function Definition
def printInfo(name, age):
2. Printing Statements
print("My name is : %s" % name)
print("And my age is : %d" % age)
➢ Purpose: These lines print the values of name and age in a formatted way.
➢ String Formatting:
✓ %s is a placeholder for a string (in this case, name).
✓ %d is a placeholder for an integer (in this case, age).
✓ The % operator is used to insert the values of the variables into the
placeholders.
P. 18 of 38
3. return Statement
return
➢ In this case, the return statement is used without any value, meaning the
function doesn't return anything explicitly.
4. Function Invocation
printInfo(age=28, name="Kimkim")
➢ Keyword Arguments:
✓ The arguments are passed as keyword arguments (age=28,
name="Kimkim"), meaning the values are explicitly associated with
the parameter names in the function.
✓ This allows arguments to be passed in any order, as long as the
parameter names are specified.
Default Arguments
A default argument is an argument that assumes a default value just in case it is not
provided in the function call for that argument.
The example below gives an idea on how default arguments are being used. It
demonstrates the way to print out default age if it is not provided.
#defaultFunc.py
ch = input('')
P. 20 of 38
Elaboration of defaultFunc.py
1. Function Definition
def printInfo(name, age=32):
➢ Parameters:
✓ name: This is a required parameter. You must provide a value for
name when calling the function.
✓ age: This is an optional parameter with a default value of 32.
If no value is provided for age when the function is called, it
will default to 32.
2. Printing Statements
print("My name is : %s" % name)
print("And my age is : %d" % age)
➢ Purpose: These lines print the values of name and age in a formatted way.
➢ String Formatting:
✓ %s is a placeholder for a string (in this case, name).
✓ %d is a placeholder for an integer (in this case, age).
✓ The % operator is used to insert the values of the variables into the
placeholders.
3. return Statement
return
➢ The printInfo function is called with the keyword arguments age=26 and
name="Kimkim".
➢ Keyword Arguments:
✓ The arguments are passed as keyword arguments, explicitly
associating the values with the parameter names in the function.
✓ This allows the arguments to be passed in any order, as long as the
parameter names are specified.
➢ The printInfo function is called with only one argument, name="Bibi". The age
parameter is not provided.
Important Notes
1. Order of Parameters:
➢ When using positional arguments (e.g., printInfo("Kimkim",
26)), the order of the arguments must match the order of the
parameters.
➢ This ensures that Python can correctly interpret the arguments when
the function is called.
P. 24 of 38
Notice that the return statement can return data in list type for caller to use in
future.
#defaultFuncModified1.py
print()
printInfo(name="Bibi")
ch = input('')
P. 25 of 38
Elaboration of defaultFuncModified1.py
1. Function Definition
def printInfo(name, age=32):
➢ Parameters:
✓ name: This is a required parameter. A value must be provided for
name when calling the function.
✓ age: This is an optional parameter with a default value of 32.
If no value is provided for age when the function is called, it
will default to 32.
➢ These lines display the values of name and age in a formatted way.
➢ String Formatting:
✓ %s is a placeholder for a string (in this case, name).
✓ %d is a placeholder for an integer (in this case, age).
✓ The % operator is used to substitute the values of the variables into
the placeholders.
3. Returning a List
return [name, age]
➢ Purpose: The function returns the name and age values as a list.
➢ A list is a mutable data structure in Python, enclosed in square brackets [],
that can hold multiple values.
➢ Example:
✓ If name = "Kimkim" and age = 26, the function will return:
["Kimkim", 26]
P. 27 of 38
➢ Keyword Arguments:
✓ The function is called with the keyword arguments age=26 and
name="Kimkim".
✓ Inside the function:
name = "Kimkim" and age = 26 are assigned.
The print statements inside the function display the values of
name and age.
➢ Return Value:
✓ The function returns the list ["Kimkim", 26].
✓ This list is assigned to the variable k.
➢ Purpose: This code iterates over the elements of the list k and prints each
element on a new line.
➢ Iterating Over k:
✓ k contains the list ["Kimkim", 26].
✓ The for loop iterates over each element in k:
On the first iteration, i = "Kimkim".
On the second iteration, i = 26.
P. 28 of 38
➢ Function Call:
✓ The printInfo function is called with only one argument,
name="Bibi". The age parameter is not provided.
defaultFuncModified2.py
#defaultFuncModified2.py
ch = input('')
Elaboration of defaultFuncModified2.py
1. Function Definition
def printInfo(name, age=32):
#print("My name is : %s" % name)
#print("And my age is : %d" % age)
return [name, age]
➢ Parameters:
✓ name: This is a required parameter. A value must be provided for
name when calling the function.
✓ age: This is an optional parameter with a default value of 32.
If no value is provided for age when the function is called, it
defaults to 32.
➢ Return Statement:
return [name, age]
➢ Keyword Arguments:
✓ The arguments are passed as keyword arguments, explicitly
associating the values with the corresponding parameter names.
✓ This allows the arguments to be passed in any order.
➢ Return Value:
✓ The list ["Kimkim", 26] is assigned to the variable k.
P. 32 of 38
➢ Purpose: This block of code prints the values stored in the list k by accessing
its elements using their indices.
➢ Indexing in Lists:
✓ Lists are zero-indexed, meaning:
The first element is accessed using index 0.
The second element is accessed using index 1.
➢ String Formatting:
✓ %s is a placeholder for a string (in this case, k[0]).
✓ %d is a placeholder for an integer (in this case, k[1]).
✓ The % operator substitutes the values into the placeholders
dynamically.
➢ Output:
✓ The print statements display:
My name is : Kimkim
And my age is : 26
P. 33 of 38
temperatureFunction.py
def toFah(theInput):
temp=(theInput*9/5)+32
return temp
ch = input("")
Elaboration of temperatureFunction.py
1. Function Definition
def toFah(theInput):
temp = (theInput * 9 / 5) + 32
return temp
➢ Parameter:
✓ theInput: This is the temperature in Celsius that is passed to the
function when it is called.
➢ Return Value:
return temp
2. Printing a Header
➢ print("The conversion report:")
✓ This line outputs a header ("The conversion report:") to indicate that a list of
temperature conversions will be displayed.
P. 35 of 38
➢ A for loop is used to iterate over the tuple (6.52, 12.19, 30.4, 60).
➢ Tuple: A tuple is an immutable data structure in Python, here containing a list
of Celsius temperatures to be converted.
➢ The variable x holds each temperature in Celsius as the loop iterates.
✓ This prints the current Celsius temperature (x) followed by a tab (\t)
and the arrow symbol (->).
✓ The end="" argument prevents the cursor from moving to the next
line, so the subsequent print statement continues on the same line.
P. 36 of 38
%8.2f specifies:
8: The total width of the field, including the number,
decimal point, and decimal places (adds padding if
necessary).
.2: The number of digits after the decimal point (2 in
this case).
f: The format specifier for a floating-point number.
➢ Example Output:
✓ If x = 6.52 and k = 43.736, the output will be:
Classwork 2
Sunlight Café is a newly opened café which provides Buffet with $138 per person.
With a view to promote the company, the boss has launched a “Buy 1 get 1 free”
promotion on buffet. That means if 2 persons come, the café will only charge the
price of 1 person. On top of this, there is a 13% service charge on the net price (net
price is the price charge without service charge).
The boss would like to have a program (Buffet – function and list.py) that can show
the net price, service charge fee and final price once after he inputs the number of
persons attend the buffet.
After user input the number of persons, the program should show all the results to
user. That is: