0% found this document useful (0 votes)
4 views32 pages

Unit4 Part01

Uploaded by

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

Unit4 Part01

Uploaded by

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

College of Science and Technology

CST Royal University of Bhutan

Unit IV – Part 01
Functions

SS2024
Introduction to Python Programming (CPL103)

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

Objectives

By the end of this session, students will be able to:


• Functions
• How to create function
• Parameter and Arguments
• Return value
• Scope
• Python Documentation - Docstrings
• Function Recursion

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

Functions

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


which runs only when it is called and NOT when the function is
defined.
• Functions take input arguments, perform operations, and return
output values. Python provides several built-in functions, and
we can also define our own functions to perform custom
operations.
Benefits of Using Functions
• Increase Code Readability
• Increase Code Reusability

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST
Without using function Royal University of Bhutan

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST
With using function Royal University of Bhutan

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

Types of Functions in Python

There are two types of function in Python Programming:


a. Built-in Library function: These are standard functions in
python that are available to use.
b. User-defined function: We can create our own functions
based on our requirements.
Create a Function
We create function using def keyword.

def greet():
print('Hello World!')
A centre of excellence in science and technology enriched with GNH values
College of Science and Technology
CST Royal University of Bhutan

To use the above function, we need to call the function.

Function call: greet()


A centre of excellence in science and technology enriched with GNH values
College of Science and Technology
CST Royal University of Bhutan

Parameter and Arguments


• Parameter: Variable/Input that is defined for the function. Listed
inside the parentheses in the function definition.
• Arguments are inputs to the function. You can add as many
arguments as you want, just separate them with a comma.

def my_function(fname): Parameter Output:


print("David" + fname) David Backham
my_function("Backham") Arguments David Villa
my_function("Villa")

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

Default Arguments, *args and key-value in function


• Python allows functions to have default argument values. Default
arguments are used when no explicit values are passed to these
parameters during a function call.
def greet(name, message="Hello"):
print(message, name)
# calling function with both Output:
arguments Good Morning Alice
greet("Alice", "Good Morning") Hello Bob
# calling function with only one
argument
greet("Bob")
A centre of excellence in science and technology enriched with GNH values
College of Science and Technology
CST Royal University of Bhutan

*args and key-value in function


Using *args allows a function to take any number of positional
arguments.
# function to sum any number of arguments
def add_all(*numbers):
return sum(numbers)
Output:
# pass any number of arguments
10
print(add_all(1, 2, 3, 4))

❖ Arguments can be also with key = value syntax

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

Cont.
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tom", child3


= "Linus")

Output:
The youngest child is Linus

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

The Return Value


We return a value from the function using the return statement.
# function definition # function definition
def my_function(x): def find_square(num):
return 5 * x result = num * num
# function call return result
print(my_function(3)) # function call
print(my_function(5)) square = find_square(3)
print(my_function(9)) print('Square:', square)
Note: Any code after return is not executed.
WAP program that uses function to compare two user input
number.
A centre of excellence in science and technology enriched with GNH values
College of Science and Technology
CST Royal University of Bhutan

Scope

❖ Region of the program where a variable is visible and


accessible.
❖ In Python, we can declare variables in three different scopes:
A. local scope
B. global, and
C. nonlocal scope.

Based on the scope, we can classify Python variables into three


types:

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

1. Local Variables

When we declare variables inside a function, these variables will


have a local scope (within the function). We cannot access them
outside the function. This is called local variables. Example:

def greet():
# local variable
message = 'Hello’ Output:
print('Local', message) Local Hello
greet() NameError: name
#outside the greet() function 'message' is not defined
print(message)
A centre of excellence in science and technology enriched with GNH values
College of Science and Technology
CST Royal University of Bhutan

2. Python Global Variables

A variable declared outside of the function or in global scope is


known as a global variable. This means that a global variable can
be accessed inside or outside of the function.

# declare global variable


message = 'Hello’
def greet(): Output:
# declare local variable Local Hello
print('Local', message) Global Hello
greet()
print('Global', message)
A centre of excellence in science and technology enriched with GNH values
College of Science and Technology
CST Royal University of Bhutan

Cont.

Exercise:

Output?
Global Variable?
Local Variable?

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

3. Nonlocal Variables

• It is a special scope that exists for nested functions


• "nonlocal" keyword is used def outer():
message = 'local’
def inner():
Output:
# declare nonlocal variable
inner: nonlocal nonlocal message
outer: nonlocal message = 'nonlocal’
Note : If we change the value of print("inner:", message)
inner()
a nonlocal variable, the changes
print("outer:", message)
appear in the local variable. outer()
A centre of excellence in science and technology enriched with GNH values
College of Science and Technology
CST Royal University of Bhutan

Python Docstrings

• Python docstrings, short for documentation strings, are the


string literals that appear right after the definition of a function,
method, class, or module.
• It is declared using '''triple single quotes''' or """ triple double
quotes """.
• The docstrings can be accessed using the _ _doc_ _ method of
the object or using the help function.
def square(n):
'''Take a number n and return the square of n.'''
return n**2

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

1. Single-line docstrings in Python


def square(n):
'''Take a number n and return the square of n.'''
return n**2
print(square.__doc__)
Or
# Using the help() function to see the docstring
help(add_numbers)
#Output: Take a number n and return the square of n.

• The closing quotes are on the same line as the opening quotes.
• There's no blank line either before or after the docstring.
• They should not be descriptive, rather they must follow "Do this, return
that" structure ending with a period.

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

2. Multi-line Docstrings in Python

• The docstring for a function or method should summarize its behavior


and document its arguments and return values.
• It should also list all the exceptions that can be raised and other
optional arguments.
help() function for Docstrings
• The help() function retrieves the docstring and displays it in a
formatted way, so users can easily understand what the function,
class, or module does.

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

❖ As you can see, we have included a short description of what


the function does, the parameter it takes in and the value it
returns.
A centre of excellence in science and technology enriched with GNH values
College of Science and Technology
CST Royal University of Bhutan

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

How docstrings is different from comments in python?

Comments
Comments in Python start with a hash mark (#) and are intended
to explain the code to developers. They are ignored by the
Python interpreter.

Docstrings
It provide a description of the function, method, class, or module.
Unlike comments, they are not ignored by the interpreter and can
be accessed at runtime using the .__doc__ attribute.

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

Function Recursion

• Recursion is a process of calling a function by itself.


• In recursion, the statements within the body of a called function
in turn calls itself(the same function).
• Two Parts:
1. Base Case:
After a finite number
of steps, it terminates its
recursion.
2. Recursive case: Calls function

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

Example 1: To find the factorial of n number

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

Recursive call steps

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

Example 2: To print the fibonacci series upto n_terms

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

Class Activity

1. Write a recursive function power(x, n) to compute x


raised to the power of n (i.e., 𝑥^𝑛) where x is the
base and n is the exponent.
2. What would happen if the base case was missing in a
recursive function?
3. How does Python keep track of the function calls when
recursion happens?

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

Home Assignment

1. What is the differences between print() and return


statement? Explain with the help of code example
2. Write notes on pow() and sqrt(). And how they are
imported.
3. Write a python program to Find Sum of Natural Numbers
Using Recursion.

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

Group Activity

• Python Lambda/Anonymous Function


• Introduction to Python map()
• filter() and
• reduce() Functions

Note: For more information visit VLE

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

Reference
Python tutorial. (n.d.). https://www.w3schools.com/python/

Automate the boring stuff with python. Automate the Boring Stuff with
Python book cover thumbnail. (n.d.). https://automatetheboringstuff.com
Programiz. (n.d.). Python Operators: Arithmetic, Comparison, Logical and
more. Www.programiz.com. https://www.programiz.com/python-
programming/operators
GfG. (2024). C Operators. GeeksforGeeks; GeeksforGeeks.
https://www.geeksforgeeks.org/quizzes/operators-gq/

A centre of excellence in science and technology enriched with GNH values


College of Science and Technology
CST Royal University of Bhutan

Thank You

SS2024
Introduction to Python Programming (CPL103)

A centre of excellence in science and technology enriched with GNH values

You might also like