0% found this document useful (0 votes)
31 views12 pages

CCD Module15-PL101 01

programming language

Uploaded by

darwinteberio0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views12 pages

CCD Module15-PL101 01

programming language

Uploaded by

darwinteberio0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

INFORMATION SHEET PL 101-15.1.

1
“Python Functions”

In this lesson, we will learn about the Python function and function expressions with the
help of examples.

References:
• Python Programming for Beginners
INFORMATION SHEET PL 101-15.1.1
“Python Functions”

A function is a block of code that performs a specific task.

Suppose, you need to create a program to create a circle and color it. You can create two functions to

solve this problem:

 create a circle function


 create a color function

Dividing a complex problem into smaller chunks makes our program easy to understand and reuse.

Types of function

There are two types of function in Python programming:

 Standard library functions - These are built-in functions in Python that are available to use.
 User-defined functions - We can create our own functions based on our requirements.

Python Function Declaration

The syntax to declare a function is:

Here,
 def - keyword used to declare a function

 function_name - any name given to the function

 arguments - any value passed to function

 return (optional) - returns value from a function

Let's see an example,

def function_name(arguments):
# function body

return
def greet():
print('Hello World!')

Here, we have created a function named greet(). It simply prints the text Hello World!.
This function doesn't have any arguments and doesn't return any values. We will learn about arguments

and return statements later in this tutorial.

Calling a Function in Python


In the above example, we have declared a function named greet().

def greet():
print('Hello World!')

Now, to use this function, we need to call it.

Here's how we can call the greet() function in Python.

# call the function


greet()

Example: Python Function


def greet():
print('Hello World!')

# call the function


greet()

print('Outside function')

Output

Hello World!
Outside function

In the above example, we have created a function named greet().

When the function is called, the control of the program goes to the function definition.

 All codes inside the function are executed.


 The control of the program jumps to the next statement after the function call.

Python Function Arguments

As mentioned earlier, a function can also have arguments. A arguments is a value that is accepted by a

function. For example,

# function with two arguments


def add_numbers(num1, num2):
sum = num1 + num2
print('Sum: ',sum)

# function with no argument


def add_numbers():
# code

If we create a function with arguments, we need to pass the corresponding values while calling them.

For example,

# function call with two values


add_numbers(5, 4)

# function call with no value


add_numbers()

Here, add_numbers(5, 4) specifies that arguments num1 and num2 will get values 5 and 4 respectively.

Example 1: Python Function Arguments


# function with two arguments
def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ",sum)

# function call with two values


add_numbers(5, 4)

# Output: Sum: 9

In the above example, we have created a function named add_numbers() with

arguments: num1 and num2.

We can also call the function by mentioning the argument name as:

add_numbers(num1 = 5, num2 = 4)

In Python, we call it Keyword Argument (or named argument). The code above is equivalent to

add_numbers(5, 4)

The return Statement in Python

A Python function may or may not return a value. If we want our function to return some value
to a function call, we use the return statement. For example,

def add_numbers():
...
return sum

Here, we are returning the variable sum to the function call.

Note: The return statement also denotes that the function has ended. Any code after return is

not executed.

Example 2: Function return Type


# function definition
def find_square(num):
result = num * num
return result

# function call
square = find_square(3)
print('Square:',square)

# Output: Square: 9

In the above example, we have created a function named find_square(). The function accepts a

number and returns the square of the number.

Example 3: Add Two Numbers


# function that adds two numbers
def add_numbers(num1, num2):
sum = num1 + num2
return sum

# calling function with two values


result = add_numbers(5, 4)

print('Sum: ', result)

# Output: Sum: 9

Python Library Functions

In Python, standard library functions are the built-in functions that can be used directly in our program.

For example,
 print() - prints the string inside the quotation marks

 sqrt() - returns the square root of a number

 pow() - returns the power of a number

These library functions are defined inside the module. And, to use them we must include the module

inside our program.


For example, sqrt() is defined inside the math module.

Example 4: Python Library Function


import math
# sqrt computes the square root
square_root = math.sqrt(4)

print("Square Root of 4 is",square_root)

# pow() comptes the power


power = pow(2, 3)

print("2 to the power 3 is",power)

Output

Square Root of 4 is 2.0


2 to the power 3 is 8

In the above example, we have used


 math.sqrt(4) - to compute the square root of 4

 pow(2, 3) - computes the power of a number i.e. 23

Here, notice the statement,

import math

Since sqrt() is defined inside the math module, we need to include it in our program.

Benefits of Using Functions

1. Code Reusable - We can use the same function multiple times in our program which makes our code

reusable. For example,


# function definition
def get_square(num):
return num * num

for i in [1,2,3]:
# function call
result = get_square(i)
print('Square of',i, '=',result)

Output
Square of 1 = 1
Square of 2 = 4
Square of 3 = 9

In the above example, we have created the function named get_square() to calculate the square

of a number. Here, the function is used to calculate the square of numbers from 1 to 3.

Hence, the same method is used again and again.

2. Code Readability - Functions help us break our code into chunks to make our program readable and

easy to understand.

Python Excercises
Exercise 1: Create a function in Python
Write a program to create a function that takes two arguments, name and age, and print their
value.

# demo is the function name


def demo(name, age):
# print value
print(name, age)

# call function
demo("Ben", 25)

Exercise 2: Create a function with variable length of arguments


Write a program to create function func1() to accept a variable length of arguments and print
their value.

Note: Create a function in such a way that we can pass any number of arguments to this function, and
the function should process them and display each argument’s value.

def func1(*args):
for i in args:
print(i)

func1(20, 40, 60)


func1(80, 100)

Exercise 3: Return multiple values from a function


Write a program to create function calculation() such that it can accept two variables and
calculate addition and subtraction.
Also, it must return both addition and subtraction in a single return call.

Solution 1:

def calculation(a, b):


addition = a + b
subtraction = a - b
# return multiple values separated by comma
return addition, subtraction

# get result in tuple format


res = calculation(40, 10)
print(res)

Solution 2:

def calculation(a, b):


return a + b, a - b

# get result in tuple format


# unpack tuple
add, sub = calculation(40, 10)
print(add, sub)

Exercise 4: Create a function with a default argument


Write a program to create a function show_employee() using the following conditions.

It should accept the employee’s name and salary and display both.
If the salary is missing in the function call then assign default value 9000 to salary.

# function with default argument


def show_employee(name, salary=9000):
print("Name:", name, "salary:", salary)

show_employee("Ben", 12000)
show_employee("Jessa")

Exercise 5: Create an inner function to calculate the addition in the following way
 Create an outer function that will accept two parameters, a and b
 Create an inner function inside an outer function that will calculate the addition of a and b
 At last, an outer function will add 5 into addition and return it
# outer function
def outer_fun(a, b):
square = a ** 2

# inner function
def addition(a, b):
return a + b

# call inner function from outer function


add = addition(a, b)
# add 5 to the result
return add + 5

result = outer_fun(5, 10)


print(result)

Exercise 6: Create a recursive function


Write a program to create a recursive function to calculate the sum of numbers from 0 to 10.

A recursive function is a function that calls itself again and again.

def addition(num):
if num:
# call same function by reducing number by 1
return num + addition(num - 1)
else:
return 0

res = addition(10)
print(res)

Exercise 7: Assign a different name to function and call it through the new name
Below is the function display_student(name, age). Assign a new name show_tudent(name, age)
to it and call it using the new name.

def display_student(name, age):


print(name, age)

# call using original name


display_student("Emma", 26)

# assign new name


showStudent = display_student
# call using new name
showStudent("Emma", 26)
STUDENT NAME: __________________________________ SECTION: __________________

PERFORMANCE TASK PL 101-15.1.1


WRITTEN WORK TITLE:

WRITTEN TASK OBJECTIVE:


MATERIALS:
 Pen and Paper
TOOLS & EQUIPMENT:
 None
ESTIMATED COST: None
Instruction:

PRECAUTIONS:
 Do not just copy all your output from the internet.
 Use citation and credit to the owner if necessary.
ASSESSMENT METHOD: WRITTEN WORK CRITERIA CHECKLIST
STUDENT NAME: _____________________________ SECTION: __________________

PERFORMANCE OUTPUT CRITERIA CHECKLIST PL 101-15.1.1

CRITERIA SCORING
Did I . . .
1 2 3 4 5
1. Focus - The single controlling point made with an awareness of a
task about a specific topic.
2. Content - The presentation of ideas developed through facts,
examples, anecdotes, details, opinions, statistics, reasons, and/or
opinions
3. Organization – The order developed and sustained within and
across paragraphs using transitional devices and including the
introduction and conclusion.
4. Style – The choice, use, and arrangement of words and sentence
structures that create tone and voice.
5. .
6. .
7. .
8. .
9. .
10. .
TEACHER’S REMARKS:  QUIZ  RECITATION 
PROJECT
GRADE:

5 - Excellently Performed
4 - Very Satisfactorily Performed
3 - Satisfactorily Performed
2 - Fairly Performed
1 - Poorly Performed

_______________________________
TEACHER

Date: ______________________

You might also like