Lukman Seminar

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 129

INTRODUCTION TO PYTHON

CAC 2216MODULE 4 FUNCTIONS

BY
Syed Lukman S N
201371601075
BSC.COMPUTER SCIENCE
SYLLABUS
CONTENTS
Functions Function calling

Features of Function The return statement

Advantages of Function Function types

Functions elements User defined function

Function syntax Built-in Function

Function definition Anonymous Function


CONTENTS
Scope of variables Time function

Pass by value Random function

Pass by reference Standard mathematics function

Function parameters
Types of function in python

Arguments in function Recursion

Types of arguments Reusable functions

Import function Functions as data


FUNCTION

• A function is a group of related statements that performs a specific task.


• Functions provide better modularity for the applications
• Functions provide a high degree of code reusing
• Programmers can write their own functions
FEATURES OF FUNCTION

• Easy to Write
• Easy to Understand
• Object-Oriented
• Robust Standard Libraries
• Supports Various Programming Paradigms
• Support for Interactive Mode
• Dynamically Typed and Type Checking
FEATURES OF FUNCTION

• Databases and GUI Programming


• Extensible
• Portable
• Scalable
• Integrated
• Automatic Garbage Collection
• Free and Open Source
Advantage of Functions in Python

• Using functions, we can avoid rewriting the same logic/code again and again in a
program
• We can call Python functions multiple times in a program and anywhere in a program
• We can track a large Python program easily when it is divided into multiple functions
• Reusability is the main achievement of Python functions
• However, Function calling is always overhead in a Python program
SYNTAX FOR CREATING FUNCTION

• Python provides the def keyword to define the function.


• The syntax of the define function is given below.
• Syntax:
• def my _ function (parameters):
function _ block
return expression
SYNTAX EXPLANATION

• Let's understand the syntax of functions definition.


• The def keyword, along with the function name is used to define the function.
• The identifier rule must follow the function name.
• A function accepts the parameter (argument), and they can be optional.
• The function block is started with the colon (:), and block statements must be at the
same indentation.
• The return statement is used to return the value. A function can have only one return
FUNCTION ELEMENTS
• Before we can use functions we have to define them.
• So there are two main elements to functions:

1. Define the function.


The function definition can appear at the beginning or end of the
program file.

2. Invoke or call the function.


This usually happens in the body of the main() function,but
subfunctions can call other sub functions too.
FUNCTION DEFINITIONS
• A function definition has two major parts:
• the definition head
• the definition body.

• The definition head in Python has three main parts:


• the keyword def, the identifier or name. of the function, and the parameters in
parentheses.

• def average (total, num):


 def = keyword
 average = identifier
(total, num) = Formal parameters or arguments
: = Don't forget the colon : to mark the start of a statement bloc
FUNCTION CALLING

• In Python, after the function is created, we can call it from another function.
A function must be defined before the function call; otherwise, the Python
interpreter gives an error. To call the function, use the function name followed
by the parentheses
• Consider the following example of a simple example that prints the message
"Hello World"
EXAMPLE

• def hello _ world():


print("hello world")
hello _ world()

• Output
hello world
THE RETURN STATEMENT
• The return statement is used at the end of the function and returns the result of the
function.
• It terminates the function execution and transfers the result where the function is called.
• The return statement cannot be used outside of the function

Syntax :
return [expression_list]
It can contain the expression which gets evaluated and value is returned to the caller
function.
If the return statement has no expression or does not exist itself in the function then it
returns the None object.
EXAMPLE
• def sum():
a = 10
b = 20
c=a+b
return c
print("The sum is :",sum ())

• Output:
The sum is: 30

 In the above code, we have defined the function named sum, and it has a statement c = a+b,
which computes the given values, and the result is returned by the return statement to the caller
function.
PROGRAM TO SOLVE
• def sum():
a = 10
b = 20
c = a+b
print(sum())

• Output:
None
In the above code, we have defined the same function without the return
statement as we can see that the sum() function returned the None object to the
caller function.
FUNCTION TYPES

• There are mainly two types of functions.

• User-define functions –
The user-defined functions are those define by the user to
perform the specific task

• Built-in functions –
The built-in functions are those functions that are pre-defined in
Python.
USER DEFINED FUNCTION
EXAMPLE 1
• def hello():
name = str(input("Enter your name: "))
if name:
print ("Hello " + str(name))
else:
print("Hello World")
return
hello()
• Output 1:
Enter your name : Syed Lukman
Hello Syed Lukman
EXAMPLE 1
• Output 2:
Enter your name :
Hello World

EXPLANATION:

In the above function, you ask the user to give a name.
If no name is given, the function will print out “Hello World”.
Otherwise, the user will get a personalized “Hello” response.
PROGRAM TO SOLVE
• def add _ numbers(x , y):
sum = x + y
return Sum
num1 = 15
num2 = 5
print("The sum is", add _ numbers (num1, num2))
• Output:
The sum is 20
PHYTHON UNICODE CODES
PYTHON BUILT-IN FUNCTIONS

• print( ) function • round( ) function


• type( ) function • len( ) function
• input( ) function • sum( ) function
• abs( ) function • divmod( ) function
• pow( ) function • ord() function
• sorted( ) function • Chr() function
• max( ) function • Isinstance() function
• min( ) function
PRINT () FUNCTION

• The print() function prints the specified message to the screen or another standard output device.

• Example 1: Print a string onto the screen:


print(“Syed Lukman”)

• Output:
Syed Lukman
TYPE() FUNCTION
• The type() function returns the type of the specified object.

• Example 1 : Return the type of the following object:


list _ of _ fruits = ('apple’, 'banana’, 'cherry’, 'mango’)
print(type(list _ of _ fruits))

• Output:
<class 'tuple'>
PROGRAM TO SOLVE
• Example 2: Return the type of the following objects:
variable_1 = “Syed Lukman”
variable_2 = 105
print(type(variable_1))
print(type(variable_2))
• Output:
<class 'str’>
<class 'int'>
INPUT() FUNCTION

• The input() function allows taking the input from the user.
Example: to write the complete message after giving the input
a = input('Enter your name :’)
print('Hello, ' + a + ' Welcome to Crescent University’)
• Output:
Enter your name : Syed Lukman
Hello, Syed Lukman Welcome to Crescent University
ABS() FUNCTION

• The abs() function returns the absolute value of the specified number.

• Example 1: Return the absolute value of a negative number


negative_number = -676
print(abs(negative_number))

• Output:
676
PROGRAM TO SOLVE

• Positive_number = 4/3
print(abs(positive_number))

• Output:
1.3
POW() FUNCTION
• The pow() function returns the calculated value of x to the power of y i.e, xy.
• If a third parameter is present in this function, then it returns x to the power of y, modulus z.
• Example 1: Return the value of 3 to the power of 4:
x = pow(3, 4)
print(x)

• Output:
81

• Example 2: Return the value of 3 to the power of 4, modulus


x = pow(3, 4, 5)
print(x)

• Output:
1
SORTED() FUNCTION
• The sorted() function returns a sorted list of the specified iterable object.
• You can specify the order to be either ascending or Descending. In this function, Strings are
sorted alphabetically, and numbers are sorted numerically.

• Example 1: Sort the specified tuple in ascending order:


tuple = ("h", "b", "a", "c", "f", "d", "e", "g")
print(sorted(tuple))
• Output:['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h’]

• Example 2: Sort the specified tuple in descending order:


tuple = ("h", "b", "a", "c", "f", "d", "e", "g")
print(sorted(tuple, reverse=True))
• Output:['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
PROGRAM TO SOLVE

• tuple = ("h", "4", "a", "c", "f", "d", "6", "g")


print(sorted(tuple))

• Output:
['4', '6', 'a', 'c', 'd', 'f', 'g', 'h']
MAX() FUNCTION
• The max() function returns the item with the maximum value.
• If the values this function takes are strings, then it is done using an alphabetical comparison.

• Example 1: Return the item in a tuple with the highest value


number_tuple = (2785, 545, -987, 1239, 453)
print(max(number_tuple))

• Output:
2785

• Example 2: Return the name with the highest value, ordered alphabetically
names_tuple = ('Dhoni’, ‘Gayle', 'Devilliers', 'Starc','Archer’)
print(max(names_tuple))
• Output:
Starc
MIN() FUNCTION
• Returns the smallest item of a list or of the typed-in arguments. It can even be a string.

• Example 1:
a=(5,7,9)
Print(min(a))
• Output:
5

• Example 2:
a=('s’, 'v’, 'z’)
Print(min(a))
• Output:
s
ROUND() FUNCTION
• The round() function returns a floating-point number that is a rounded version of the specified number, with
the specified number of decimals.

• Example 1: Round the specified positive number to the nearest integer:


nearest_number = round(87.76432)
print(nearest_number)

• Output:
88

• Example 2: Round the specified negative number to the nearest integer:


nearest_number = round(-87.76432)
print(nearest_number)

• Output:
-88
PROGRAM TO SOLVE

• Round the specified number to the nearest integer:


nearest_number = round(87.46432)
print(nearest_number)
• Output:
87
LEN() FUNCTION
• The len() function returns the count of items present in a specified object.
• When the object is a string, then the len() function returns the number of characters present in that string.

• Example 1: Return the number of items in a list


fruit_list = ["apple", "banana", "cherry", "mango", "pear"]
print(len(fruit_list))
• Output:
5

• Example 2: Return the number of items in a string object


string = "Crescent University“
print(len(string))
• Output:
19
SUM() FUNCTION
• The sum() function returns a number, the sum of all items in an iterable.

• Example 1: Print the sum of all the elements of a list


list = [1, 2, 3, 4, 5]
print(sum(list))
• Output:
15

• Example 2:
a = (1, 2, 3, 4, 5)
print(sum(a, 7))
• Output:
22
DIVMOD() FUNCTION
• The divmod() function returns a tuple containing the quotient and the
remainder when the first argument i.e, the dividend is divided by the second
argument i.e, the divisor.

• Example 1: Display the quotient and the remainder when 7 is divided by 3


x = divmod(7, 3)
print(x)
• Output:
(2, 1)
ORD() FUNCTION
• The ord() function returns the number representing the Unicode code of a specified character.

• Example 1: Return the integer that represents the character “h”:


x = ord("h")
print(x)
• Output:
104

• Example 2: Return the integer that represents the character “H”:


x = ord("H")
print(x)
• Output:
72
CHR() FUNCTION
• The ord() function returns the CHARACTER representing the Unicode code of a
specified NUMBER.

• Example 1:
x = chr(115)
print(x)
• Output:
s

• Example 2:
x = chr(88)
print(x)
• Output:
X
PROGRAM TO SOLVE

• Y=chr(64)
print(Y)

• OUTPUT:
@
ISINSTANCE() FUNCTION
• The isinstance() function returns True if the specified object is of the specified type, others
False.

• Syntax: isinstance(object, type)

• EXAMPLE:
number= 23
print (isinstance(number, int))
print (isinstance(number, str))
print (isinstance(number, float))

• OUTPUT:
True
False
False
PROGRAM TO SOLVE

• X = “Syed Lukman”
Y=5
A=(‘apple’, ‘mango’)
B=[‘banana’, ‘cherry’]
Z=10.0
C={“name”: “Lukman”, “age”:19}
print (isinstance(Y, int))
print (isinstance(A, tuple))
print (isinstance(X, str))
print (isinstance(C, dict))
print (isinstance(Z, float))
print (isinstance(B, list))
OUTPUT

True
True
True
True
True
True
ANONYMOUS FUNCTION

• Lambda functions in python, also known as anonymous functions are


those which don't possess a name. In general, while declaring or
defining a function, we use the def keyword along with a name for the
function. But in the case of lambda functions, we use the keyword
lambda (hence the name lambda function) and then define the function.

• Syntax of lambda function: lambda arguments : expression


EXAMPLE
• # normal function
def square(a):
return a*a;
# lambda function
anon_fun = lambda a: a*a
print("Using lambda function:")
print(anon_fun(12))
print("Using regular function:")
print(square(12))

• Output:
Using lambda function:144
Using regular function:144
PROGRAM TO SOLVE

n= lambda x,y: x**y


x=int (input("Enter value of x :"))
y=int(input("Enter value of y :"))
print('x power y is:',n(x,y))

• OUTPUT:
Enter value of x: 50
Enter value of y :3
x power y is: 125000
BUILT-IN VS USED DEFINED FUNCTION

• Built-in functions are those that are already defined in Python libraries and
we can call them directly. User defined functions are those that we define
ourselves in our program and then call them wherever we want.
SCOPE OF VARIABLE
Scope of a variable is the portion of a program where the variable is recognized.

• There are two basic scopes of variables in Python:


 Global variables
Local variables

• Global Scope -variables defined outside the function and part of main
program

• Local Scope - variables defined inside functions have local scope


GLOBAL VS LOCAL VARIABLE

• Variables that are defined inside a function body have a local


scope, and those defined outside have a global scope.
• This means that local variables can be accessed only inside
the function in which they are declared.
• Global variables can be accessed throughout the program
body by all functions.
• When you call a function, the variables declared inside it are
brought into scope.
EXAMPLE
• Def my_func():
y=10
print(“value inside the function:”,y)
my_func()
y=20
print (“value outside the function:”,y)

• Output:
value inside the function: 10
value outside the function: 20
EXAM PL E

• total= 50 # This is global variable.


def sum (arg1, arg2 ):
total = arg1 + arg2 # Here total is Local variable.
print("Inside the function local total : ", total)
return total
sum ( 10, 20)
print("Outside the function global total : ", total)

• Output:
Inside the function local total : 30
Outside the function global total : 50
PROGRAM TO SOLVE
• add=10
def sum(a,b):
tot=a+b
print("The local value of total is:",tot)
sum(12,3)
print("The global value of total is:", add)

OUTPUT:
The local value of total is:15
The global value of total is:10
HOW TO CALL A FUNCTION

•There are two ways to call a function either by PASSING A VALUE or PASSING REFERENCE .
•PASSING BY VALUE
•Example:
# passing by value
a=20
def func(b):
print("The value of b is:",b)
b=50
print("The new value of b is:",b)
# calling a function passing by value
func (a)

•Output:
The value of b is: 20
The new value of b is: 50
PASSING BY REFERENCE
• Example:
# passing by reference
a=[10,20,30]
def sum (b):
print("The value of b is:",b)
b[0]=40
b[1]=50
print("The new value of b is:",b)
# calling a function passing by refernce
sum (a)

• Output:
The value of b is: [10, 20, 30]
The new value of b is: [40, 50, 30]
FUNCTION PARAMETERS

• A parameter is the variable listed inside the parentheses in the function


definition.
• In Python, Parameter refers to the information passed to the function.
• Parameters are also known as arguments.
• A parameter is a special kind of variable, used in a function to refer to one of
the pieces of data provided as input to the function to utilise.
• These pieces of data are called arguments.
• Parameters are Simply Variables.
• Typically, Parameters are of two types – Formal Parameters, Actual
Parameters
PARAMETER TYPES

• A functions has two types of parameter(s):

1.Formal Parameter: Formal Parameters are the parameters which


are specified during the definition of the function.

2. Actual Parameter: Actual Parameters are the parameters which


are specified during the function call.
EXAMPLE
• def ADD(x, y):
z=x+y
print("Sum = ", z)
a=float(input("Enter first number: " ))
b=float(input("Enter second number: " ))
ADD(a,b)
#Calling the function by passing actual parameters.

• Output:
Enter first number: 10
Enter second number: 20
Sum= 30.0

• In the above example, x and y are formal parameters. a and b are actual parameters.
EXAMPLE
• def evenodd(x):
if x%2==0:
print("It is an even number")
else:
print("It is a odd number")
n=int (input("Enter any number:"))
evenodd(n)

• OUTPUT:
Enter any number:5
It is a odd number
• OUTPUT:
Enter any number:8
It is an even number
PROGRAM TO SOLVE

• def sum(a, b):


c = a +b
print (‘The sum is:’,c)
x = 10; y = 15
sum(x, y)

• OUTPUT:
The sum is: 25
ARGUMENTS IN FUNCTION

• An argument is the value that is sent to the function when it is called.


• The arguments are types of information which can be passed into the
function.
• The arguments are specified in the parentheses.
• We can pass any number of arguments, but they must be separate them with a
comma.
Example

• def func (name):


print("Hi ",name)
func("Lukman")

• Output:
Hi Lukman
PROGRAM TO SOLVE

• def python (name):


print(name, ‘from Crescent University’)
python (‘Lukman’)|

• OUTPUT:
Lukman from Crescent University
TYPES OF ARGUMENTS

• There may be several types of arguments which can be passed at the time of
function call.
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
REQUIRED ARGUMENTS

• Required arguments are the arguments passed to a function incorrect


positional order. Here, the number of arguments in the function call should
match exactly with the function definition To call the function printme(), you
definitely need to pass one argument, otherwise it gives a syntax error
EXAMPLE

def result(name, marks):


print("Name of student : ", name)
cgpa = marks/10
print("CGPA is : ", cgpa)
result(“Dhoni",95)
KEYWORD ARGUMENTS

• Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the
parameter name. This allows you to skip arguments or place them out of
order because the Python interpreter is able to use the keywords provided to
match the values with parameters. You can also make keyword calls to the
printme() function
EXAMPLE

def result(name, marks):


print("Name of student : ", name)
cgpa = marks/10
print("CGPA is : ", cgpa)
result(marks=95,name=“Dhoni")
DEFAULT ARGUMENTS

• Python allows us to initialize the arguments at the function definition. If the


value of any of the arguments is not provided at the time of function call, then
that argument can be initialized with the value given in the definition even if
the argument is not specified at the function call.
Example

• def func(name , age=10):


print("My name is ",name , “ and age is ", age)
func(name = “Surya")

• Output:
My name is Surya and age is 10
PROGRAM TO SOLVE

def result(name, marks=90):


print("Name of student : ", name)
cgpa = marks/10
print("CGPA is : ", cgpa)
result(“Dhoni",95)
VARIABLE LENGTH ARGUMENT

• A variable length argument as the name suggests is an argument that can


accept variable number of values. To indicate that the function can take
variable number of argument you write a variable argument using a ‘*’, for
example *args.
EXAMPLE
• def add_num(*args):
sum = 0
for num in args:
sum += num
return sum
result = add_num(5, 6, 7) print('Sum is', result)
result = add_num(5, 6, 7, 8) print('Sum is', result)
result = add_num(5, 6, 7, 8, 9) print('Sum is', result)

• Output:
Sum is 18
Sum is 26
Sum is 35
IMPORT FUNCTION

i) PYTHON IMPORT STATEMENT ENABLES THE USER TO IMPORT PARTICULAR MODULES IN THE CORRESPONDING PROGRAM.

ii) Import in python is similar to #include header_file in C/C++

SYNTAX: IMPORT MODULE_NAME

EXAMPLE: IMPORT COLLECTIONS


TIME FUNCTION

➤ PYTHON HAS A MODULE NAMED TIME TO HANDLE TIME RELATED TASKS.

➤ TO USE FUNCTIONS DEFINED IN THEMODULE:WE NEED TO IMPORT THE MODULE FIRST

➤ IMPORT TIME

➤ THE TIME PACKAGE CONTAINS A NUMBER OF FUNCTIONS THAT RELATE TO TIME. WE WILL
CONSIDER SOME FUNCTIONS LIKE: SLEEP AND TIME
PYTHON TIME.SLEEP()
➤ THE SLEEP FUNCTION SUSPENDS (DELAYS) EXECUTION OF THE CURRENT
THREAD FOR THE GIVEN NUMBER OF SECONDS.

EXAMPLE 1: PYTHON SLEEP()

import time
print(“computer")
time.sleep(2.4)
print(“science")

OUTPUT:

computer
science

➤ “computer" is printed. Suspends (Delays) execution for 2.4 seconds.


“science" is printed.
As you can see from the above example,sleep() takes a floating-point number as an
argument.
PROGRAM TO SOLVE

• import time
print(“Logged in.")
time.sleep(3)
print(“Logged out.")

• OUTPUT:
Logged in.
Logged out.
( after 3 seconds)
RANDOM FUNCTION

SOME IMPORTANT FUNCTION OF THE RANDOM


MODULE

• RANDOM.RANDINT()
• RANDOM.CHOICE()
• RANDOM.SHUFFLE()
RANDOM.RANDINT()
➤ THIS FUNCTION USED TO GET A RANDOM NUMBER BETWEEN
THE TWO GIVEN NUMBERS
➤ THIS FUNCTION TAKES TWO VALUES WHICH ONE IS A
LOWERLIMIT AND ANOTHER ONE IS THE UPPER LIMIT

• EXAMPLE:
IMPORT RANDOM
PRINT(‘A RANDOM INTEGER IS:’)
PRINT(RANDOM.RANDINT(1,10))

• OUTPUT:
RUN 1: A RANDOM INTEGER IS: 4
RUN 2: A RANDOM INTEGER IS: 6
RUN 3: A RANDOM INTEGER IS: 8
RANDOM.CHOICE()

➤ THIS FUNCTION RETURNS A RANDOM VALUE FROM A LIST


WHICH MAY BE AN INTEGER OR A FLOAT VALUE OR STRING.

➤ IT TAKES A LIST AS AN ARGUMENT AND LIKE THE RANDINT


FUNCTION IT ALSO GIVES A DIFFERENT VALUE FROM THE
GIVEN LIST FOR EACH TEST CASE.

EXAMPLE:
IMPORT RANDOM
A=[1,2,5, ‘ LUKMAN’, ‘KUMAR’, 3.5, ‘INCLUDE’, ‘HELP’]
PRINT(A RANDOM VALUE FROM THE GIVEN LIST:)
PRINT(RANDOM.CHOICE(A))
OUTPUT

• RUN 1:A RANDOM VALUE FROM THE GIVEN LIST: 3.5


• RUN 2: A RANDOM VALUE FROM THE GIVEN LIST:HELP
• RUN 3:A RANDOM VALUE FROM THE GIVEN LIST: 5
• RUN 4:A RANDOM VALUE FROM THE GIVEN LIST: 2
RANDOM.SHUFFLE()

• THIS FUNCTION IS USED TO MIX THE ELEMENTS OF THE GIVEN LIST IN


RANDOM ORDER.
• IT TAKES A LIST AS AN ARGUMENT AND LIKE OTHERFUNCTIONS OF THE
RANDOM MODULE.

• EXAMPLE:
import random
A=[“apple”, “banana”, “cherry”]
random.shuffle(A)
print(‘NEW LIST AFTER SHUFFLING:’,A)

• OUTPUT:
NEW LIST AFTER SHUFFLING : [‘cherry’, ‘apple’, ‘banana’]
TYPES OF FUNCTIONS IN PYTHON

1.Python Function with no argument and no return value.

2.Function with no argument and with a Return value.

3.Python Function with argument and No Return value.

4.Function with argument and return value.


1.Python Function with no argument and no return value

def Adding():
a = 20
b = 30
C=a+b
print(“THE SUM IS :", Sum)
Adding()

OUTPUT:
THE SUM IS : 50
2.Function with no argument and with a Return value

def Multiply():
a = 10
b = 25
C=a*b
Return C
print(“THE MULTIPLICATION IS : ", Multiply())

OUTPUT:
THE MULTIPLICATION IS : 250
3.Python Function with argument and No
Return value

def subtract(a, b):


C= a - b
print(“THE SUBTRACTION IS:", C)
Subtract(60, 20)

OUTPUT:
THE SUBTRACTION IS : 20
4.Function with argument and return value

def divide(a, b):


c=a/b
return c
print(“THE DIVISION IS:", divide(36,4))

OUTPUT:
THE DIVISION IS : 9.0
THANK YOU

You might also like