1 of 82

USER DEFINED FUNCTIONS

2 of 82

HTML

XML

VOIP

FTP

HTTP

SIP

POP

SMTP

IMAP

SMS

3 of 82

A function is a subprogram that acts on data and often returns a value

Consider the following example

f(x) = 2x

  1. f(2) = ?
  2. f(4) = ?
  3. f(6) = ?

def calc(x) :

a=2*x

return a

4 of 82

Creating a Function��

  • In Python a function is defined using the def keyword.

5 of 82

Calling a Function�

  • To call a function, use the function name followed by parenthesis:

6 of 82

User Defined Functions

  • In Python, it is also possible for programmer to write their own function(s). These functions can then be combined to form module which can be used in other programs by importing them.
  • To define a function, keyword 'def' is used.
  • After the keyword comes an identifier i.e. name of the function, followed by parenthesized list of parameters and the colon which ends up the line, followed by the block of statement(s) that are the part of function.

7 of 82

Calling and using Function

  • To use a function that has been defined earlier, you need to write a function call statement
  • eg Consider the function

Y=cube(4)

print(Y)

print(cube(4))

8 of 82

The following function can be called in one of the following way:

  1. Function with no argument

cube()

ii) Passing variable as argument in function call

num=10

cube(num)

iii) Taking input and Passing the input as argument in function call

num=int(input(‘Enter the number’))

cube(num)

  1. Passing literal as argument in function call

cube(5)

9 of 82

The following function can be called in one of the following way:

iv) using function call inside another statement

print(cube(5))

v) Using function call inside expression

ans=2*cube(4)

10 of 82

Case 1

11 of 82

Case 2

12 of 82

Case 3�Passing parameter and no return type

13 of 82

Case 3-Taking input and Passing the input as argument in function call�Passing parameter and no return type

14 of 82

Case 4�Passing parameter and return type

15 of 82

Case 4�function used in expression

16 of 82

17 of 82

How to call the function greet?

greet()

How to call the function sum?

a=sum(4,6)

x,y=5,6

a=sum(x,y)

18 of 82

Write the order in which the statement gets executed.

2

3

4

5

1

6

19 of 82

Arguments�

  • Information can be passed into functions as arguments.
  • Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
  • The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:

20 of 82

def my_function(fname):�  print(fname + " Hello")�

#main �my_function(“Sarah")�my_function(“Toby")�my_function(“Mick")

Sarah Hello

Toby Hello

Mick Hello

21 of 82

22 of 82

  1. Write a Program using functions to find the sum of 2 numbers, the function will not have parameter and no return type.

  • Write a Program using functions to find the sum of 2 numbers, the function will not have parameter and return type.

  • Write a Program using functions to print the cube of a number, the function will take a parameters.

4. Write a Program using functions to print sum of the series 13+23+33+43+53+………N3 where a function cube_no(a) is called each time to find the cube of a number

23 of 82

  •  

24 of 82

Write a menu driven pgm with each options as functions

  1. Accept a sentence from the user.
  2. Print the number of words in the sentence
  3. Print the number of digits in the sentence
  4. Print each word and its length.
  5. Print the pallendrome words from the sentence.

25 of 82

STRUCTURE OF A PYTHON PROGRAM

  • In a python program, generally all function definitions are given at the top followed by statement which are not part of any functions.
  • These statements are not indented at all.
  • These are often called from the top-level statements
  • Internally python gives a special name to top level as _main_

26 of 82

def fun1():

:

def fun2():

:

#top-level statements here

stmt1

stmt2

27 of 82

  • Python stores this name in a built-in variable called __name__ which will store the value __main__

28 of 82

Flow of execution in a function call

  • The flow of Execution refers to the order in which statement are executed during a program run

29 of 82

Parameters or Arguments?�

  • The terms parameter and argument can be used for the same thing: information that are passed into a function.
  • From a function's perspective:
  • A parameter is the variable listed inside the parentheses in the function definition.
  • An argument is the value that are sent to the function when it is called.

30 of 82

Number of Arguments�

  • By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.

31 of 82

Example�

  • This function expects 2 arguments, and gets 2 arguments:
  • def my_function(fname, lname):�  print(fname + " " + lname)��my_function(“BGS ", “NPS")

32 of 82

This function expects 2 arguments, but gets only 1:�

  • def my_function(fname, lname):�  print(fname + " " + lname)��my_function(“BGS")

33 of 82

Passing parameters

  • The values being passed through a function call statement are called argument(or actual argument or actual parameter).

  • The values received in the function header/ definition are called parameters(or formal parameter or formal argument)

  • Python supports three types of formal argument/parameters

34 of 82

Passing parameters

  • The values being passed through a function call statement are called argument(or actual argument or actual parameter).

  • The values received in the function header/ definition are called parameters(or formal parameter or formal argument)

  • Python supports three types of formal argument/parameters

35 of 82

Python supports three types of formal argument/parameter

  • Positional argument (Required arguments)
  • Default argument
  • Keyword ( or named) arguments

36 of 82

1. Positional arguments (Required arguments)

  • When the function call statement must match the number and order of argument as defined in the function definition, this is called the positional argument.
  • In this you need to match the number of arguments with number of parameters required

def check(a,b,c):

:

check(x,y,z) # 3 values (all variables) passed

check(2,x,y) #3 values(1 literal+2var) passed

check(2,3,5) #3 values(3 literals) passed

37 of 82

2. Default arguments

  • A parameter having default value in the function header is known as a default parameter
  • A parameter having a default value in the function header becomes optional in the function call.
  • Function call may or may not have value for it

38 of 82

Default Parameter Value�

  • The following example shows how to use a default parameter value.

  • If we call the function without argument, it uses the default value:

39 of 82

40 of 82

  • For eg :

def interest(prin , time, rate =0.10) # legal

def interest(prin , time=2, rate =0.10) #legal

def interest(prin , time=2, rate )

#illegal ( default parameter before required parameter )

def interest(prin=100 , time, rate =0.10) #illegal

def interest(prin=100 , time=2, rate =0.10) #legal

41 of 82

3. Keyword Arguments

  • You can also send arguments with the key = value syntax.

  • This way the order of the arguments does not matter.�

42 of 82

3. Keyword Arguments

  • Python offers a way of writing function calls where you can write any argument in any order provided you name the arguments
  • interest(prin=2000 , time=3, rate =0.10)
  • interest(time=3 ,prin=2000 ,rate =0.10)
  • interest(rate =0.10 ,time=3 ,prin=2000)

43 of 82

44 of 82

45 of 82

Passing a List as an Argument�

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the function:

46 of 82

47 of 82

Return Values�

  • To let a function return a value, use the return statement.
  • A function may or may not return a value
  • Functions returning value are known as fruitful functions.
  • Functions that does not return a value is known as non-fruitful function.
  • A function can just use return keyword without returning any value, In that case it will return None value back

48 of 82

Return Values�

  • To let a function return a value, use the return statement.

15

25

49 of 82

50 of 82

The pass Statement�

  • Function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error.

51 of 82

Function can return a multiple values

  • To return multiple values from a function, you have to ensure the following things:
  • The return statement inside a function body should be of the form given below:

return <value1/var1>, <value2/var2>, etc

52 of 82

ii) The function call statement should receive or use the returned values in one of the following ways:

a) Either receive the returned values in the form a tuple variable

def square(x,y,z):

return x*x,y*y,z*z

#__main__

t=square(2,3,4)

print(t)

(4,9,16)

53 of 82

b) You can directly unpack the received values of tuple by specifying the same number of variables on the left- hand side of the assignment in function call

def square(x,y,z):

return x*x,y*y,z*z

#__main__

a,b,c=square(2,3,4)

print(a,”@”,b,”@”,c)

4@9@16

54 of 82

SCOPE OF VARIABLES

  • Part(s) of program within which a name is legal and accessible is called scope of the name
  • Example in real life (Ticket)
  • There are broadly two kinds of scopes in Python:
  • Global Scope
  • Local Scope

55 of 82

Global variable

  • A name/variable declared in top level segment of a program is said to have global scope and is used inside the whole program and all blocks(function, other blocks) contained within the program.

56 of 82

Local Scope

  • A name/variable declared in a function-body is said to have local scope i.e, it can be used only within this function and the other blocks contained under it.

57 of 82

Global variables:

Num1,num2,s

Local variables:

x,y,z

58 of 82

59 of 82

60 of 82

x,y,z& sm is local

a,b,c & s is local

Num1, num2, num3 are Global

61 of 82

NAME RESOLUTION�(Resolving scope of a Name)

For every name reference within a program i.e, when you access a variable from within a program or function, Python follows name resolution rule also known as LEGB RULE.

Python does the following to resolve it:

62 of 82

i) It checks within its Local environment (LEGB), If it has a variable within the same name , if yes, Python uses its value�if not, then it moves to step (ii)

63 of 82

ii) Python now checks for the enclosing environment(LEGB) i.e whether there is a variable modified in the enclosing body.

If not them moves to the next step(iii)

64 of 82

Enclosing (or nonlocal) scope is a special scope that only exists for nested functions. If the local scope is an inner or nested function, then the enclosing scope is the scope of the outer or enclosing function. This scope contains the names that you define in the enclosing function.

65 of 82

iii) Python now checks for the Global environment(LEGB).

If not them moves to the next step(iv)

66 of 82

iv) Python now checks for the Built in environment(LEGB).

If none of the steps finds a variable then it will gibe a

Name error

Variable not found

67 of 82

68 of 82

Let us consider some examples

Case 1: Variable in Global Scope but not in Local Scope

69 of 82

Case 2: Variable neither in Global Scope or Local Scope

70 of 82

Case 3: Some Variable name in local Scope as well as Global Scope

71 of 82

What if you want to use the global variable inside local scope?

  • If you want to use the global variable inside a local function without modifying it, simply use the variable.
  • But if you want to make any changes to the global variable , then python makes use of the global statement.
  • The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are part of the global environment.

72 of 82

73 of 82

MUTABLE/ IMMUTABLE PROPERTIES OF PASSED DATA OBJECTS

74 of 82

75 of 82

76 of 82

  • In case a mutable data type is passed into the function, any changes made to the variable in the function is reflected back to the variable in the main function.

77 of 82

PROGRAMS

  1. W.A.P using functions ( with parameter & return type) to calculate the area of a circle.

  • W.A.P using functions ( with parameter & no return type) for converting cm to feet & inches [ 1 ft=12 inches, 1 inch=2.54cm]
  • W.A.P to accept 2 no's M,n return the value M  (using with only one parameter and return type)

  • W.A.P to accept X from a user & return square of X.

78 of 82

5. W.A.P using function to find the average of 3 given numbers and return the average

6. W.A.P using function to accept a number from the user and find the factorial of a number.

7. W.A.P using function to accept a number from the user and returns 1 if the number is positive else 0 if the number is negative.

8. W.A.P using function to accept a number from the user and print the stars in the ascending order

*

**

***

79 of 82

9. W.A.P using function to accept a number  N from the user and find the Fibonacci series till the term N.

10. W.A.P using function to accept a string from the user and pass each character into the function and count the number of digits in the string.

11. W.A.P using function to enter the mark of a student return the grade back.

(100-90 ‘A’,

75-90 ‘B’,

50-75 ‘C’,

ELSE ‘D’ )

80 of 82

  •  

81 of 82

14. Using function that takes one char as parameter and prints out the next five character separated by #

15. Program that invokes a function calc which take 2 integers and an arithmetic operator as parameter and prints the corresponding result.

82 of 82

15. Program that invokes a function calc which take 2 integers and an arithmetic operator as parameter and prints the corresponding result.

16. Function called pall which accepts the number as parameter (no return type) and print if it is a palindrome or not.

17. Using function call convert that accepts an alphabet as a parameter and return the upper case or the lower-case value.