Lab 6 Functions
Lab 6 Functions
Lab 6 Functions
Code Once
Introduction to Computers
Laboratory Manual
Experiment #6
Functions
Experiment #6: Functions
What is Function?
A function is a block of organized, reusable code that is used to perform a single related action.
Functions can be used to define reusable code and organize and simplify code.
As you already know, Python gives you many built-in functions like print(), input(), etc. But you
can also create your own functions. These functions are called user-defined functions.
Defining a Function
A function definition consists of the function’s name, parameters, and body. The syntax for
defining a function is as follows:
Ex: The following function prints the statement "Hi, from IUG" 3 times.
def print_hi():
for i in range(3):
print "Hi, from IUG"
Note that if we run the previous program it will print nothing. The previous code defines a
function, but still we need to invoke that function to be executed.
Calling a Function
Calling (invoking) a function executes the code in the function.
In a function’s definition, you define what it is to do. To use a function, you have to call or invoke
it. The program that calls the function is called a caller.
The following code invokes the method print_hi() which we defined previously:
print_hi()
Note that any function must be defined before it can be called. Thus, the following code is
correct:
2
Experiment #6: Functions
def print_hi():
for i in range(3):
print "Hi, from IUG"
print_hi()
However, the following code is wrong and will not run correctly:
print_hi()
def print_hi():
for i in range(3):
print "Hi, from IUG"
Ex: Write a function that takes a string as a parameter and prints that string 3 times to the
screen. Then invoke the function to print "Hi, Amazing day!".
def print_s(string):
for i in range(3):
print string
Note that if we called the later method without passing a parameter, we will get an error and
the code will not run correctly.
• A function contains a header and body. The header begins with the def keyword,
followed by the function’s name and parameters, and ends with a colon.
• A parameter is like a placeholder: When a function is invoked, you pass a value to the
parameter. This value is referred to as an actual parameter or argument. Parameters
are optional; that is, a function may not have any parameters.
• The function body contains a collection of statements that define what the function
does.
3
Experiment #6: Functions
A function that does not return a value is known as a void function. The call to void functions
must be a statement. For example, the print_hi function does not return a value so the following
call is a statement:
print_hi()
A function that returns a value is known as a value-returning function, and if the function
returns a value, a call to that function is usually treated as a value. For example, the input()
function is a value-returning function, it returns the value entered by the user. The following
code illustrates the idea.
Suppose the user entered the number 3, the previous code is now equivalent to this:
num = 3
So, the interpreter substitutes the return value 3 for entire function invocation.
To write a value-returning function we use the return keyword to indicate the value to be
returned to the caller.
Note that the max function is a value-returning function, so, the returned value should be stored
in a variable to be used later. We can invoke the previous function as follows:
larger = max(5, 8)
print(larger)
print(max(3, 4))
4
Experiment #6: Functions
which prints the return value of the function call max (3, 4).
sum(3, 4)
print(sum(3, 4))
If the argument is a number or a string, the argument is not affected, regardless of the changes
made to the parameter inside the function. The following code illustrates the idea:
def increment(n):
n += 1
print("n inside the function is", n)
def main():
x = 1
print("Before the call, x is", x)
increment(x)
print("After the call, x is", x)
5
Experiment #6: Functions
As shown in the output, the value of x (1) is passed to the parameter n to invoke the increment
function. The parameter n is incremented by 1 in the function, but x is not changed no matter
what the function does.
You can use nPrintln("hello", 3) to print hello three times. The nPrintln("hello", 3) statement
passes "hello" to message, passes 3 to n, and prints hello three times. When we call a function
like this, it is said to use positional arguments. The arguments must match the parameters in
order, number, and compatible type, as defined in the function header.
You can also call a function using keyword arguments, passing each argument in the form
name = value. For example, nPrintln(n = 5, message = "good") passes 5 to n and "good" to
message. The arguments can appear in any order using keyword arguments.
Default Arguments
Python allows you to define functions with default argument values. The default values are
passed to the parameters when a function is invoked without the arguments.
The following example illustrates how to define functions with default arguments and how to
call such functions:
6
Experiment #6: Functions
n1, n2 = sort(10, 7)
print("n1 is", n1)
print("n2 is", n2)
('n1 is', 7)
7
Experiment #6: Functions
Lab Work
Ex1: Write a function that take two numbers, x and y, and returns the sum of number from x to
y.
Solution:
Now we can use sum_range function to sum numbers between 0 -10, 1-100 and 100-150.
Ex2: Write a function that returns the absolute value of a number. If the function was called
without any arguments, it should return the absolute of 1.
Solution:
def absolute_value(num=1):
if num >= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
print(absolute_value())
Ex3: Write a function that prints the grade for a given score. Then use the function to print the
score entered by user.
Solution:
8
Experiment #6: Functions
def print_grade(score):
if score >= 90.0:
print('A')
elif score >= 80.0:
print('B')
elif score >= 70.0:
print('C')
elif score >= 60.0:
print('D')
else:
print('F')
Ex4: Write a function isPrime that determines whether an integer is a prime number or not.
(A prime number is a natural number greater than 1 that has no positive divisors other than 1
and itself).
Solution:
def isPrime(num):
if num < 2:
return False
for i in range(2, num):
if (num % i) == 0:
return False
return True
9
Experiment #6: Functions
Homework
1. Write factorial(num) function that computes the factorial of an integer.
2. Write a function print_prime_numbers(num) that prints all the prime numbers up to num.
(hint: use isPrime function from the lab work.)
3. Using the following function header, write a function that computes the distance
between two points.
def distance(x1, y1, x2, y2):
5. Write a function that computes the sum of the digits in an integer. Use the following
function header:
def sum_digits(n):
For example, sum_digits(234) returns 9, which is the sum of 2 + 3 + 4.
Good Luck
10