0% found this document useful (0 votes)
119 views52 pages

Functions in Python

The document discusses user-defined functions in Python. It explains that a function is a block of reusable code that performs a specific task. Functions contain parameters, a docstring, code block, and return statement. Functions can call other functions, including recursively calling themselves. The document also provides examples of defining, calling, and using a recursive function. It demonstrates how functions use a stack to manage recursive calls.

Uploaded by

Raviraj kundekar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
119 views52 pages

Functions in Python

The document discusses user-defined functions in Python. It explains that a function is a block of reusable code that performs a specific task. Functions contain parameters, a docstring, code block, and return statement. Functions can call other functions, including recursively calling themselves. The document also provides examples of defining, calling, and using a recursive function. It demonstrates how functions use a stack to manage recursive calls.

Uploaded by

Raviraj kundekar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 52

Functions

User defined functions


• A function is a block of organized, reusable
code that is used to perform a single, related
action. Functions provide better modularity
for your application and a high degree of code
reusing.
Defining a Function

• Function blocks begin with the keyword def followed


by the function name and parentheses ( ( ) ).
• Any input parameters or arguments should be placed
within these parentheses
• The first statement of a function can be an optional
statement - the documentation string of the function
or docstring.
• The code block within every function starts with a
colon (:) and is indented.
• The statement return [expression] exits a function,
optionally passing back an expression to the caller.
• Syntax
def functionname( parameters ):
"function_docstring“
function_statements
return [expression]
#function def
def fact(n):
"this function calculates factorial of n"
f=1
for c in range(1,n+1):
f=f*c
return f
#main prog
n=int(input("Enter a num:"))
f=fact(n)
print("Fact=",f)
Recursive Function
• In the Python world, a function can call another
function and a function can call itself as well.
• Ex.
def rec(n):
if n<=0:
return o/p:
Enter no3
print('n=",n) n= 3
n= 2
rec(n-1) n= 1

n=int(input("Enter no"))
rec(n)
Stack Diagram
def fact(n):
f=1
if n>0:
f=n*fact(n-1)
return f
else:
return 1

n=int(input("Enter no"))
f=fact(n)
print("Fact=",f)
f=1
n=3
n=3 3*fact(3-1)
if n>0 ???? 2
f=f*fact(n-1)
n=2
Back to main 2*fact(2-1)
1

n=1
1*fact(1-1)

1
n=0
Return 1
Strings
• Strings are amongst the most popular types in
Python.
• We can create them simply by enclosing
characters in quotes.
• Python treats single quotes the same as
double quotes.
• For example −
str1 = 'Hello World!'
str2 = "Python Programming“
Accessing Strings
• In Python strings are stored as individual
characters in a continuous memory location.
• Strings can be accessed in both directions in
Python i.e. backward and forward
• Forward indexing starts with 0,1,2,…
• Backward indexing starts with -1,-2,-3,…
0 1 2 3 4

H E L L O

-5 -4 -3 -2 -1
Ex. 1
str="hello"
for i in range(-5,0):
print (str[i],end="")
Ex. 2
str="hello"
for i in range(0,5):
print (str[i],end="")
• Traversing using for loop:
Ex.
str="hello"
for i in str:
print (i,end="")

o/p hello
Traversing using while loop
Ex.
str="hello"
i=0
while i<len(str):
print (str[i],end="")
i=i+1
o/p:hello
String Slices
Extracting the subset of string is called as string
Slice (using [] operator)
Syntax: string[start:end]
This will return part of the string from start to
index end -1
String Comparison
Python compares strings using ASCII value.
Comparison operators(>,<,>=,<=,==,!=) are used
to compare strings.
>>> "python"=="python"
True
>>> "Python"=="python"
False
>>> "python">="Python"
True
The IN and NOT IN Operator
• These Boolean operators takes two string .
• In return true if first string appears as subsstring in second.
>>> str="Hello Python"
>>> 'h' in str
True
>>> 'c' in str
False
>>> 'h' not in str
False
>>> 'c' not in str
True
>>>
String Methods
•String.capitalize():Capitalize first letter of string
Ex:
>>>“sam”.capitalize()
>>>Sam
•String.Find(str,beg=0,end=len(string)):
Determines if substring occurs in string and returns -
1 if string not found.
>>>"hello and welcome".find("e")
>>>1
>>>"hello and welcome".find("e",2)
>>>11
>>> "hello and welcome".find("z",1)
>>>-1
String Methods
• String.rfind(str,beg=0,end=len(string)):
Same as find but search backward in string.
>>> "hello and welcome".rfind("e")
16
>>> "hello and welcome".rfind("e",0,5)
1
String Methods
• String.Count(str,beg=0,end=len(string))
Count how may times str occures in string.
Ex.
>>> "hello and welcome".count("e")
3
>>> "hello and welcome".count("e",5)
2
String Methods
• String.index(str,beg=0,end=len(string)):
Returns index same as found but throws an
exception if not found
>>>hello and welcome".index("e")
>>>1
>>>"hello and welcome".index("z",1)
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
"hello and welcome".index("z",1)
ValueError: substring not found
String Methods
String.islower():returns true if string has atleast
1 cased character.
>>> "sam".islower()
True
>>> "SAM".islower()
False
>>>
String Methods

String.isupper():returns true if string has atleast


1 cased character.
>>> "sam".isupper()
False
>>> "SAM".isupper()
True
String Methods
Str.isalpha():returns true if string contains all
alphabetic char otherwise false
>>> "hello".isalpha()
True
>>> "123".isalpha()
False
>>> "a12".isalpha()
False
String Methods
String.isdigit(): returns true if string contain only
digit and false otherwise.
>>> "123".isdigit()
True
>>> "1sam".isdigit()
False
String Methods
String.lower():converts all uppercase letters into
lowercase letters.
String.upper(): converts all lowercase letters into
uppercase letters.
>>> "Sam".upper()
'SAM'
>>> "Sam".lower()
'sam'
>>>
String Methods
• max(String):Returns the max alphabetical
character from string
• Min(String):Returns the min alphabetical
character from string.
>>> max("sam")
's'
>>> min("sam")
'a'
String Methods
• replace(old,new,[max]):Replace all
occurrences of old character from string with
new char or at most max occurrences if max
given.
>>> "hello and welcome".replace("e","*")
'h*llo and w*lcom*'
>>> "hello and welcome".replace("e","*",2)
'h*llo and w*lcome'
>>>
String Methods
• String.split( delimeter=“”):Split string into
number of substring according to
delimeter.(By default delimiter is space)
>>> "hello and welcome".split()
['hello', 'and', 'welcome']
>>> "hello".split()
['hello']
>>> "welcome*to*python".split("*")
['welcome', 'to', 'python']
String Methods
• String.swapcase():Inverts case for all letters in
string.
>>> "Sam".swapcase()
'sAM‘
Type Conversion Function
• Python provides built in functions that convert values
from one type to other.
• int(): It converts strings and float values in to integers.
>>> int('23')
23
>>> int(3.45)
3
• float(): It converts string and integer to float values.
>>> float('23.3')
23.3
>>> float(23)
23.0
Type Conversion Function

• str(): It converts float, integers, list, tuple,


dictionary in to string values.
>>> str(10)
'10'
>>> str([1,2,3])
'[1, 2, 3]'
Math Function
• The math module is standard module in
python and is always available .
• To use mathematical function user need to
import module using-
import math
• And call function as
math.function_name(Parameter)
Interactive mode:
>>> import math
>>> math.sqrt(100)
10.0

Script Mode:
import math
print(math.sqrt(100))
Function Description Example

ceil(x) It returns integer greater >>> math.ceil(34.4)


than or equal to x. 35
>>> math.ceil(34.0)
34
fabs(x) Returns absolute value of x >>> math.fabs(34.64)
34.64
>>> math.fabs(34)
34.0
floor(x) Returns integer less than or >>> math.floor(34.3)
equal to x. 34
fmod(x,y) Returns the remainder when >>> math.fmod(10,3)
x/y 1.0
Function Description Example
modf(x) Returns fractional and >>> math.modf(10.23)
integer part of x (0.23000000000000043,
10.0)
exp(x) Returns e**x >>> math.exp(4.0)
54.598150033144236
>>> math.exp(1)
2.718281828459045
log(x,[base]) Returns the log of x to >>> math.log(100)
the base(default e) 4.605170185988092
>>> math.log(100,2)
6.643856189774725
pow(x,y) Returns x raised to y >>> math.pow(2,3)
8.0
sqrt(x) Returns square root of x >>> math.sqrt(100)
10.0
Function Description Example

cos(x) Returns cosine, sine and tan >>> math.sin(0)


sin(x) value of x 0.0
tan(x) >>> math.cos(0)
1.0
>>> math.tan(0)
0.0
degree(x) Converts angle x from >>> math.radians(90)
radians to degree 1.5707963267948966
radians(x) Converts angle x from degree >>> math.degrees(90)
to radians 5156.620156177409
Constant: Represents mathematical 3.14159…
pi constant
E Standard mathematical 2.71828…
constant
Composition
• Composition in python means that you have two
or more functions where the output of one
function is input of another function.
• Syntax
funB(funA(x))
Where x is input for funA and the result of that is
input for funB.
Ex. import math
print(math.sqrt(100))
Fruitful functions and void functions
• Some of the functions we are using, such as the
math functions, yield results, called as fruitful
functions.
• Other functions perform an action but don't
return a value. They are called void functions.
• Result given by fruitful function might be assign
to a variable or use it as part of an expression:
x = math.cos(radians)
y = (math.sqrt(5) + 1) / 2
Fruitful functions and void functions
• Void functions might display something on the
screen or have some other effect, but they
don't have a return value.
• If you try to assign the result to a variable, you
get a special value called None.
Ex.

def disp():
print("******")
#main
a=disp()
print (a)
import
• There are many built in libraries, module and
packages are provided by Python.
• These libraries we can use using import
statement.
• There are two ways to use import statements-
1. Import statement
2. From import statement
3. From..import * statement
import statement:
It import a module and access definitions using dot
operator.
Syntax:
import m1[,m2,m3,..]
Ex.
>>> import math, time
>>> print(math.sqrt(100),"\n",time.time())
10.0
1498580005.252804
from ..import statement
from..import statement is used to import
specific attributes from a module.
Syntax: from modulename import a1[,a2,a3..]
Ex.
>>> from math import pi
>>> print(pi)
3.141592653589793
from.. Import * statement
To import all items from module.
Syntax:
from modulename import *
Ex.
>>> from math import *
>>> print(pi, e)
3.141592653589793 2.718281828459045
Boolean Function
• This function return true or false
def fun(n):
if n%2==0:
return True
else:
return False
n=int(input("Enter num:"))
print(fun(n))
Incremental Development
• The goal of incremental development is to
avoid long debugging sessions by adding and
testing only small code at a time.
• As example suppose if u want to find roots of
quadratic equations.
The formula for annual compound interest, including
principal sum, is: A = P (1 + r/n) (nt)
Where:

A = the future value of the investment/loan, including


interest
P = the principal investment amount (the initial deposit
or loan amount)
r = the annual interest rate (decimal)
n = the number of times that interest is compounded
per year
t = the number of years the money is invested or
borrowed for
• Step 1 : Define outline for function
define input (parameters)and output (return
value).
In this case p, r, n and t are input parameters.
The return value is compound interest(float type
value) .
Out line-
def comint(p,r,n,t):
return 0.0
Run--o/p
#main
a=comint(0,0,0,0)
print(a)
• If an amount of Rs. 5,000 is deposited into a
savings account at an annual interest rate of
5%, compounded monthly, the value of the
investment after 10 years can be calculated as
follows...
• P = 5000. r = 5/100 = 0.05 (decimal). n = 12. t
= 10.
• If we plug those figures into the formula, we
get:
• A = 5000 (1 + 0.05 / 12) ^ (12(10)) = 8235.05
• Step 2: At the point we have confirmed that
the function is syntactically correct, we can
start adding code to the body.
Use variable to hold intermediate values so
you can display and check them.
def comint(p,r,n,t):
I=(1+(r/n)) o/p
It=I**(n*t)
print('I=',I)
print('It=',It)
return 0.0
#main
a=comint(5000,0.05,12,10)
print(a)
Step 3: If the function is working correctly add
next step of calculation.
def comint(p,r,n,t):
I=(1+(r/n))
It=I**(n*t)
print('I=',I)
print('It=',It)
A=p*It
print(A)
return 0.0
#main
a=comint(5000,0.05,12,10)
print(a)
• Step 4: Check final answer and if that works
correctly return result .
• Also try to consolidate multiple statements
into compound statements.
def comint(p,r,n,t):
It=(1+(r/n))**(n*t)
return(p*It)
#main
a=comint(5000,0.05,12,10)
print("Compound Intr=",a)

You might also like