Unit-1 Part-2
Unit-1 Part-2
Unit-1 Part-2
FUNCTIONS
If a group of statements is repeatedly required then it is not recommended to write these
statements every time separately. 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 functions which are coming along with Python software automatically, are called
built in functions or pre-defined functions.
Eg:
id()
type()
input()
eval()
etc..
2. User defined functions
All the functions that are written by any us comes under the category of user defined
functions. Below are the steps for writing user defined functions in Python.
• In Python, def keyword is used to declare user defined functions.
• An indented block of statements follows the function name and arguments which contains
the body of the function.
Syntax:
def function_name():
statements
Example:
# Declaring a function
def fun():
print("Inside function")
# Driver's code
# Calling function
fun()
Parameters
Parameters are inputs to the function. If a function contains parameters, then at the timeof
calling, compulsory we should provide values otherwise, otherwise we will get error.
Return Statement:
Function can take input values as parameters and executes business logic, and returns
output to the caller with return statement.
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:\Python_classes>py test.py
9. The sum is 30
10. The sum is 300
1. positional arguments:
2. keyword arguments:
Sometimes we can pass variable number of arguments to our function, such type ofarguments
are called variable length arguments.
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
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:
a=10 # global variable
def f1():
print(a)
def f2():
print(a)
f1()
f2()
output:
10
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:
def f1():
a=10
print(a)
def f2():
print(a)
f1()
f2()
output:
10
a is not defined
Lambda Functions in Python are anonymous functions, implying they don't have a name. The def
keyword is needed to create a typical function in Python, as we already know. We can also use the
lambda keyword in Python to define an unnamed function.
Note: By using Lambda Functions we can write very concise code so that readability of the
program will be improved.
5) Output
6) The Square of 4 is : 16
7) The Square of 5 is : 25
In Python, we know that a function can call other functions. It is even possible for the function to call
itself. These types of construct are termed as recursive functions.
The following image shows the working of a recursive function called recurse.
Advantages of Recursion
1) def factorial(n):
2) if n==0:
3) result=1
4) else:
5) result=n*factorial(n-1)
6) return result
7) print("Factorial of 4 is :",factorial(4))
8) print("Factorial of 5 is :",factorial(5))
9)
10) Output
factorial(3)=3*factorial(2)
=3*2*factorial(1)
=3*2*1*factorial(0)
=3*2*1*1
=6
factorial(n)= n*factorial(n-1)
import modulename
import module1,module2,module3 import
module1 as m
import module1 as m1,module2 as m2,module3 from module
import member
from module import
member1,member2,memebr3
from module import memeber1 as x
from module import *
This module defines several functions which can be used for mathematical operations. The
main important functions are
1. sqrt(x)
2. ceil(x)
3. floor(x)
4. fabs(x)5.log(x)
6. sin(x)
7. tan(x)
....
Eg:
We can use these functions while developing games, in cryptography and to generate random
numbers on fly for authentication.
Code
0.3232640977876686
Code
215
Code
Code
M
765
54
Code
Any sequence of characters within either single quotes or double quotes is considered as a
String.
Syntax:
s='durga'
s="durga"
Eg:
>>> ch='a'
>>> type(ch)
<class 'str'>
We can define multi-line String literals by using triple single or double quotes.
Eg:
We can also use triple quotes to use single quotes or double quotes as symbol inside String
literal.
s='durga'
Eg:
>>> s='durga'
>>> s[0]
'd'
>>> s[4]
'a'
>>> s[-1]
'a'
>>> s[10]
IndexError: string index out of range
2. Accessing characters by using slice operator:
Syntax: s[bEginindex:endindex:step]
We can use len() function to find the number of characters present in the string.
Eg:
s='d
urga
'
print
(len(
s))
#5
Finding Substrings:
We can use the following 4 methods
For forward direction:
find()
index(
)
For backward direction:
rfind()
rindex()
1. find():
s.find(substring)
Returns index of first occurrence of the given substring. If it is not available then
we will get -1
Eg:
2) print(s.find("Python")) #9
3) print(s.find("Java")) # -1
4) print(s.find("r"))#3
5) print(s.rfind("r"))#21
index() method:
Output:
D:\python_classes>py test.py
Enter main string: learning python is very easy Enter sub string: python
substring found
We can find the number of occurrences of substring present in the given string by
using count() method.
s.replace(oldstring,newstring)
inside s, every occurrence of oldstring will be replaced with newstring.