• No results found

05_Functions.pdf

N/A
N/A
Protected

Academic year: 2020

Share "05_Functions.pdf"

Copied!
27
0
0

Loading.... (view fulltext now)

Full text

(1)

Functions

Nihar Ranjan Roy

[email protected], [email protected] Department of Computer Science and Engineering

GD Goenka University, Gurugram

Home Page:https://sites.google.com/site/niharranjanroy/

(2)

Outline

1 Functions

2 Syntax

3 Function with default arguments

4 Functions with keyword arguments

5 Scope of variables

6 Returning multiple values from a function

7 Recursive function

8 Lambda Function

(3)

Functions

Functions

Functions are a set of instructions grouped together that perform special task and are called by an identifier assigned to it called function name. Functions has several advantages

Code becomes smaller

Readability

Modularity Re-usability

(4)

Syntax

Syntax

The keyword def introduces a function definition.

It must be followed by the function name and the parenthesized list of formal parameters.

The statements that form the body of the function start at the next line, and must be indented.

def name_of_function(Parameters):

"""docstring"""

statement1\\ statement2\\

.\\

.\\

(5)

Syntax

Problem

Write a function for finding sum of the number within a range specified by the user.

sum(5,7)

sum is 18 (5+6+7=18)

(6)

Syntax

Solution

#sum of number in a range

def sumrange(a,b):

sum=0

for i in range(a,b+1):

sum=sum+i

return sum

#call function

print("Sum is ",sumrange(5,7))

(7)

Syntax

Problem

Write a program to generate Fibonacci series of n terms whose first two terms are 0 and 1.

(8)

Syntax

Solution

def fib(n): # argument to the function

"""function to generate Fibonacci series upto n"""

a, b = 0, 1 while a <n:

print(a, end=' ') a,b=b,a+b

print()

(9)

Function with default arguments

Functions with default arguments

It is possible to assign default value to parameters in Python, if no parameter is passed then default value is used.

#function with default arguments def sum(a=4,b=5):

return(a+b)

#calling function

print(sum(2,2)) # calling with parameters

print(sum()) #calling without parameters

(10)

Functions with keyword arguments

Functions with keyword arguments

If a programmer knows the parameter names,he/she can use it to pass arguments to functions.

def display( Name, Mobile):

print(Name, "has mobile number", Mobile)

#call to function

(11)

Functions with keyword arguments

Precautions:Functions with keyword arguments

def display( Name, Mobile):

print(Name, "has mobile number", Mobile)

1 A positional argument cannot follow a keyword argument.Example

display(Mobile=1234567,’Nihar’)

2 Cannot duplicate an argument by both specifying it as keyword

argument and positional argument. Example display(’Nihar’,Name=’Ranjan’)

(12)

Scope of variables

Scope of variables in python I

#this program demonstrates variable scope

var1=4 def func():

var1=7

print("inside func()"+str(var1))

print("outside function"+str(var1)) func()

(13)

Scope of variables

Scope of variables in python II

——–output————– outside function4 inside func()7 outside function4

(14)

Scope of variables

Scope of variables in python III

#this program demonstrates variable scope

var1=4 def func():

global var1 var1=7

print("inside func()"+str(var1))

print("outside function"+str(var1)) func()

(15)

Scope of variables

Scope of variables in python IV

——–output————– outside function4 inside func()7 outside function7

(16)

Scope of variables

Problem

Write a function to accept an integer and tell if it is an Armstrong number or not.

Example: 153, has 3 digits

so (1)3+ (5)3+ (3)3 = 1 + 125 + 27 = 153

(17)

Returning multiple values from a function

Returning multiple values from a function

#returning multiple values from function

def compute (no1,no2):

return no1+no2, no1-no2

#calling function sum,diff =compute(7,5)

print("sum and difference of two

numbers is ",sum, "and ",diff)

Output:

sum and difference of two numbers is 12 and 2

(18)

Recursive function

Recursive function

if a function calls itself again and again till a terminating condition is reached is called recursive function.

#recursive factorial of number def factorial(no):

if no==1:

return 1

return no*factorial(no-1)

#call function factorial

no=5

(19)

Lambda Function

Lambda Function

These are also know as anonymous functions. Such functions are not

bound to any name

#lambda function

cube=lambda x:x*x*x #define lambda function print(cube(3)) #call lambda function

Note:

Lambda function doesnot contain return statement

It contain single statement/ expression in its body.

(20)

Lambda Function

Problem

(21)

Lambda Function

Solution

def DecimalToBinary(n):

if n>0:

print(n%2,end=' ') n=n//2

DecimalToBinary(n)

#calling function

print("MSB is on right") DecimalToBinary(7)

print("\n")

DecimalToBinary(17)

print("\n")

DecimalToBinary(27)

———–OUTPUT——————-MSB is on right 1 1 1

1 0 0 0 1 1 1 0 1 1

(22)

Lambda Function

User defined module

Its a two step process

1 User the import keyword to import the previously defined module

example ”UserModule”

import UserModule

2 To user function or variables from the module prefix it with the name

of the module

(23)

User defined module

Problem

Create user define module named ”UserModule” and inside that create a function DToB for converting a decimal number to binary. Also using this module convert an integer number to binary

(24)

User defined module

Solution-I

def DToB(n): s=""

while n>0:

s=s+str(n%2) n=n//2

print(s[::-1])

if __name__=="__main__":

n=int(input("Please enter an integer"))

(25)

User defined module

Solution-II

import UserModule

print("Using a user defined module") UserModule.DToB(23)

———–OUTPUT——————-Using a user defined module 1 1 1 0 1

(26)

Exercises

Exercises I

1. Write a function to find reverse of an integer number.

2. List the steps involved in creating a user defined module and use it.

3. On the basis of following function

def display(Name, Mobile):

print(Name, ”has mobile number”,Mobile)

What will be the output for the following calls? Give your comments wherever necessary

i. display(Mobile=1234567890,Name=’Nihar’)

ii. display(Mobile=1234567890,’Nihar’)

iii. display(’Nihar’,Mobile=1234567890)

iv. display(Mobile=1234567890,’12343454’)

(27)

Exercises

Exercises II

4. What do you understand by scope of a variable? Explain usage of

global keyword with an example

5. Write a function to convert a number from binary to decimal.

6. Write a recursive function to printnth fibonacci series term.

7. Is it possible in python to return multiple values from a function?

Illustrate it with an example.

References

Related documents

You fill in the data sources and format is to a form that excel exports to create a single excel to your computer science in order data from.. You just need to click the ok button

Automatic Tests of Business Processes Test module Create debitor Create material Create request Create offer Expor t t Export Import Import Create request Debitor number Material

Upon arriving at the laser center, you will be greeted and have the opportunity to ask any remaining questions regarding this consent. Before proceeding with your ASA procedure,

Nevertheless, Howard and Hatfield summarize her work on total aphasia (comprehension deficit and severe expressive disorder present); “Expressive speech is regained in the most

The Symantec Government licensing program streamlines the procurement process for Symantec security and availability products, as well as support and maintenance service

In the Edit PDF Portfolio pane, open the Select A Color Scheme section.. In the Select A Color Scheme section, click Customize

To convert a decimal number into its octal equivalent, the same procedure is adopted as in decimal to binary conversion but the decimal number is divided by 8 (the base of the

Convert 35 in decimal to binary, we start with the number in Convert 35 in decimal to binary, we start with the number in decimal and move to the left while continuously finding the