Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
58 views

Functions: 50, Lakhanpur Housing Society, Behind Lucky Restaurant, Vikas Nagar, Kanpur 208024

1) Functions allow grouping of related statements to perform repeatable tasks. They improve code reuse and readability. There are two types of functions - built-in and user-defined. User-defined functions are defined using the def keyword. 2) Functions can take input parameters and return outputs. Parameters provide inputs to functions while return statements return outputs. Functions can return single or multiple values. 3) Variable scope in functions is determined by whether a variable is declared globally or locally. Global variables defined outside functions are accessible within and outside functions while local variables are only accessible within the function body. The global keyword makes global variables accessible for modification within functions.

Uploaded by

ashutosh pandey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Functions: 50, Lakhanpur Housing Society, Behind Lucky Restaurant, Vikas Nagar, Kanpur 208024

1) Functions allow grouping of related statements to perform repeatable tasks. They improve code reuse and readability. There are two types of functions - built-in and user-defined. User-defined functions are defined using the def keyword. 2) Functions can take input parameters and return outputs. Parameters provide inputs to functions while return statements return outputs. Functions can return single or multiple values. 3) Variable scope in functions is determined by whether a variable is declared globally or locally. Global variables defined outside functions are accessible within and outside functions while local variables are only accessible within the function body. The global keyword makes global variables accessible for modification within functions.

Uploaded by

ashutosh pandey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

FUNCTIONS

If a group of statements is repeatedly required then it is not recommended to write these


statements every time seperately.We have to define these statements as a single unit and
we can call that unit any number of times based on our requirement without rewriting.
This unit is nothing but function.
The main advantage of functions is code Reusability.
Note: In other languages functions are known as methods, procedures etc
Python supports 2 types of functions
1. Built in Functions
2. User Defined Functions
1. Built in Functions:
The functions which are coming along with Python software automatically, are called
built in functions or pre-defined functions
Eg:
id()
type()
input()
etc..
2. User Defined Functions:
The functions which are developed by programmer explicitly according to business
requirements, are called user defined functions.
Syntax to create user defined functions:
def function_name(parameters) :
""" doc string"""
----
-----
return value

Note: While creating functions we can use 2 keywords


1. def (mandatory)
2. return (optional)
Eg 1: Write a function to print Hello
test.python:
1) def wish():
2) print("Hello Good Morning")
3) wish()
4) wish()
5) wish()

Parameters
Parameters are inputs to the function. If a function contains parameters,then at the time
of calling,compulsory we should provide values otherwise,otherwise we will get error.
Eg: Write a function to take name of the student as input and print wish message by
name.
1. def wish(name):

50,Lakhanpur Housing Society,Behind Lucky Restaurant,Vikas Nagar,Kanpur


208024
2. print("Hello",name," Good Morning")
3. wish("raja")
4. wish("Rani")
5.
6.
7. D:\Pythonthon_classes>python test.python
8. Hello raja Good Morning
9. Hello Rani Good Morning

Eg: Write a function to take number as input and print its square value
1. def squareIt(number):
2. print("The Square of",number,"is", number*number)
3. squareIt(4)
4. squareIt(5)
5.
6. D:\Pythonthon_classes>python test.python
7. The Square of 4 is 16
8. The Square of 5 is 25

Return Statement:
Function can take input values as parameters and executes business logic, and returns
output to the caller with return statement.
Q. Write a function to accept 2 numbers as input and return sum.
1. def add(x,y):
2. return x+y
3. result=add(10,20)
4. print("The sum is",result)
5. print("The sum is",add(100,200))
6.
7.
8. D:\Pythonthon_classes>python test.python
9. The sum is 30
10. The sum is 300

If we are not writing return statement then default return value is None
Eg:
1. def f1():
2. print("Hello")
3. f1()
4. print(f1())
5.
6. Output
7. Hello
8. Hello
50,Lakhanpur Housing Society,Behind Lucky Restaurant,Vikas Nagar,Kanpur
208024
9. None

Q. Write a function to check whether the given number is even or odd?


1. def even_odd(num):
2. if num%2==0:
3. print(num,"is Even Number")
4. else:
5. print(num,"is Odd Number")
6. even_odd(10)
7. even_odd(15)
8.
9. Output
10. D:\Pythonthon_classes>pythonthon test.python
11. 10 is Even Number
12. 15 is Odd Number

Returning multiple values from a function:


In other languages like C,C++ and Java, function can return atmost one value. But in
Python, a function can return any number of values.
Eg 1:
1) def sum_sub(a,b):
2) sum=a+b
3) sub=a-b
4) return sum,sub
5) x,y=sum_sub(100,50)
6) print("The Sum is :",x)
7) print("The Subtraction is :",y)
8)
9) Output
10) The Sum is : 150
11) The Subtraction is : 50

Types of arguments
def f1(a,b):
------
------
------
f1(10,20)
a,b are formal arguments where as 10,20 are actual arguments
There are 4 types are actual arguments are allowed in Python.
1. positional arguments
2. keyword arguments
3. default arguments
4. Variable length arguments
1. positional arguments:

50,Lakhanpur Housing Society,Behind Lucky Restaurant,Vikas Nagar,Kanpur


208024
These are the arguments passed to function in correct positional order.
def sub(a,b):
print(a-b)
sub(100,200)
sub(200,100)
The number of arguments and position of arguments must be matched. If we change the
order then result may be changed.
If we change the number of arguments then we will get error.

2. keyword arguments:
We can pass argument values by keyword i.e by parameter name.
Eg:
1. def wish(name,msg):
2. print("Hello",name,msg)
3. wish(name="Raja",msg="Good Morning")
4. wish(msg="Good Morning",name="Raja")
5.
6. Output
7. Hello Raja Good Morning
8. Hello Raja Good Morning

Here the order of arguments is not important but number of arguments must be matched.
Note:
We can use both positional and keyword arguments simultaneously. But first we have to
take positional arguments and then keyword arguments,otherwise we will get syntax
error.
def wish(name,msg):
print("Hello",name,msg)
wish("Raja","GoodMorning") ==>valid
wish("Raja",msg="GoodMorning") ==>valid
wish(name="Raja","GoodMorning") ==>invalid
SyntaxError: positional argument follows keyword argument
3. Default Arguments:
Sometimes we can provide default values for our positional arguments.
Eg:
1) def wish(name="Guest"):
2) print("Hello",name,"Good Morning")
3)
4) wish("Raja")
5) wish()
6)
7) Output
8) Hello Raja Good Morning
9) Hello Guest Good Morning

If we are not passing any name then only default value will be considered.
***Note:

50,Lakhanpur Housing Society,Behind Lucky Restaurant,Vikas Nagar,Kanpur


208024
After default arguments we should not take non default arguments
def wish(name="Guest",msg="Good Morning"): ===>Valid
def wish(name,msg="Good Morning"): ===>Valid
def wish(name="Guest",msg): ==>Invalid
SyntaxError: non-default argument follows default argument
4. Variable length arguments:
Sometimes we can pass variable number of arguments to our function,such type of
arguments are called variable length arguments.
We can declare a variable length argument with * symbol as follows
def f1(*n):
We can call this function by passing any number of arguments including zero number.
Internally all these values represented in the form of tuple.

Eg:
1) def sum(*n):
2) total=0
3) for n1 in n:
4) total=total+n1
5) print("The Sum=",total)
6)
7) sum()
8) sum(10)
9) sum(10,20)
10) sum(10,20,30,40)
11)
12) Output
13) The Sum= 0
14) The Sum= 10
15) The Sum= 30
16) The Sum= 100

Note:
We can mix variable length arguments with positional arguments.

Eg:
1) def f1(n1,*s):
2) print(n1)
3) for s1 in s:
4) print(s1)
5)
6) f1(10)
7) f1(10,20,30,40)
8) f1(10,"A",30,"B")
9)
10) Output

50,Lakhanpur Housing Society,Behind Lucky Restaurant,Vikas Nagar,Kanpur


208024
11) 10
12) 10
13) 20
14) 30
15) 40
16) 10
17) A
18) 30
19) B

Note: After variable length argument,if we are taking any other arguments then we
should provide values as keyword arguments.
Eg:
1) def f1(*s,n1):
2) for s1 in s:
3) print(s1)
4) print(n1)
5)
6) f1("A","B",n1=10)
7) Output
8) A
9) B
10) 10

f1("A","B",10) ==>Invalid
TypeError: f1() missing 1 required keyword-only argument: 'n1'

Note: Function vs Module vs Library:


1. A group of lines with some name is called a function
2. A group of functions saved to a file , is called Module
3. A group of Modules is nothing but Library

Types of Variables
Python supports 2 types of variables.
1. Global Variables
2. Local Variables
1. Global Variables
The variables which are declared outside of function are called global variables.
These variables can be accessed in all functions of that module.
Eg:
1) a=10 # global variable
2) def f1():
3) print(a)

50,Lakhanpur Housing Society,Behind Lucky Restaurant,Vikas Nagar,Kanpur


208024
4)
5) def f2():
6) print(a)
7)
8) f1()
9) f2()
10)
11) Output
12) 10
13) 10

2. Local Variables:
The variables which are declared inside a function are called local variables.
Local variables are available only for the function in which we declared it.i.e from outside of
function we cannot access.
Eg:
1) def f1():
2) a=10
3) print(a) # valid
4)
5) def f2():
6) print(a) #invalid
7)
8) f1()
9) f2()
10)
11) NameError: name 'a' is not defined

global keyword:
We can use global keyword for the following 2 purposes:
1. To declare global variable inside function
2. To make global variable available to the function so that we can perform required
modifications
Eg 1:
1) a=10
2) def f1():
3) a=777
4) print(a)
5)
6) def f2():
7) print(a)
8)
9) f1()

50,Lakhanpur Housing Society,Behind Lucky Restaurant,Vikas Nagar,Kanpur


208024
10) f2()
11)
12) Output
13) 777
14) 10
Eg 2:
1) a=10
2) def f1():
3) global a
4) a=777
5) print(a)
6)
7) def f2():
8) print(a)
9)
10) f1()
11) f2()
12)
13) Output
14) 777
15) 777

Eg 3:
1) def f1():
2) a=10
3) print(a)
4)
5) def f2():
6) print(a)
7)
8) f1()
9) f2()
10)
11) NameError: name 'a' is not defined

Eg 4:
1) def f1():
2) global a
3) a=10
4) print(a)
5)
6) def f2():
7) print(a)

50,Lakhanpur Housing Society,Behind Lucky Restaurant,Vikas Nagar,Kanpur


208024
8)
9) f1()
10) f2()
11)
12) Output
13) 10
14) 10

Note: If global variable and local variable having the same name then we can access global
variable inside a function as follows
1) a=10 #global variable
2) def f1():
3) a=777 #local variable
4) print(a)
5) print(globals()['a'])
6) f1()
7)
8)
9) Output
10) 777
11) 10

50,Lakhanpur Housing Society,Behind Lucky Restaurant,Vikas Nagar,Kanpur


208024

You might also like