Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python unit 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

Functions & Strings

UNIT 2
Janhavi Vadke
FUNCTIONS
• A function is a block of organized, reusable
code that is used to perform a single, related
action.
• Functions provide better modularity for the
application and a high degree of code reusing.
• Classification of functions
1) Library functions or Built in functions
2) User defined functions
Defining a Function
• Rules to define a function in Python are
• 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. We can also define parameters
inside 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. A return
statement with no arguments is the same as return None.
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
Calling a Function
• Once the basic structure of a function is finalized, we
can execute it by calling it from another function or
directly from the Python prompt
• def printme( str ):
"This prints a passed string into this function"
print (str)
return
• # Now we can call printme function
• printme("This is first call to the user defined function!")
• printme("Again second call to the same function")
math function
• The math module is a standard module in python
and is always available. To use mathematical
functions under this module you have to import
the module using import math and call the
function as math.function_name(parameter)
• math.pow(x, y)
Return x raised to the power y
• math.sqrt(x)
Return the square root of x.
• math.ceil(x)
Return the ceiling of x, the smallest integer greater than or
equal to x. If x is not a float, delegates to x.__ceil__(), which
should return an Integral value.
• math.fabs(x)
Return the absolute value of x.
• math.floor(x)
Return the floor of x, the largest integer less than or equal to x.
If x is not a float, delegates to x.__floor__(), which should
return an Integral value.
• math.fmod(x, y)
Return fmod(x, y), as defined by the platform C library. Note
that the Python expression x % y may not return the same
result
• math.trunc(x)
Rounds up or down towards zero.
Type Conversion Functions
• Sometimes it is necessary to convert values from one type
to another. Python provides a few simple functions that will
allow us to do that.
• int() - constructs an integer number from an integer literal,
a float literal or a string literal
• float() - constructs a float number from an integer literal, a
float literal or a string literal
• str() - constructs a string from a wide variety of data types,
including strings, integer literals and float literals
• long(x) to convert x to a long integer.
• print(float("123.45"))=123.45
• x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Composition
• Composition means that you have two or more
functions where the output of one function is the
input for another.
• Function composition is a way of combining
functions such that the result of each function is
passed as the argument of the next function.
• Function B(FunctionA(x))
• Eg
• >>>Import math
• >>>math.floor(math.sin(45))
Flow of execution
• We have to create a function before we can run it. In other
words, the function definition has to run before the
function gets called.
• Execution always begins at the first statement of the
program. Statements are run one at a time, in order from
top to bottom. Function definitions do not alter the flow of
execution of the program, but remember that statements
inside the function don’t run until the function is called.
• A function call is like a detour in the flow of execution.
Instead of going to the next statement, the flow jumps to
the body of the function, runs the statements there, and
then comes back to pick up where it left off.
• When it gets to the end of the program, it terminates.
Parameters and arguments
• Information can be passed to functions as parameter.
• Parameters are specified after the function name, inside the
parentheses. You can add as many parameters as you want, just
separate them with a comma.
• def print_twice(bruce):
print(bruce)
print(bruce)
This function assigns the argument to a parameter named bruce.
When the function is called, it prints the value of the parameter
(whatever it is) twice.
>>> print_twice('Spam')
o/p Spam
Spam
1)Required arguments
Required arguments are the arguments passed to a function in correct
positional order. Here, the number of arguments in the function call should
match exactly with the function definition.
2)Keyword arguments
• When you use keyword arguments in a function call, the caller identifies
the arguments by the parameter name.
• This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the
values with parameters.
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function“
print ("Name: ", name)
print ("Age ", age )
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )
3)Default Parameter Value
A default argument is an argument that assumes a default
value if a value is not provided in the function call for that
argument
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age )
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )
The return Statement
• The statement return [expression] exits a function,
optionally passing back an expression to the caller. A return
statement with no arguments is the same as return None.
• def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print ("Inside the function : ", total )
return total;
# Now you can call sum function
total = sum( 10, 20 );
print ("Outside the function : ", total)
Scope of Variables
• All variables in a program may not be accessible
at all locations in that program. This depends on
where you have declared a variable.
• The scope of a variable determines the portion of
the program where you can access a particular
identifier. There are two basic scopes of variables
in Python −
• Global variables
• Local variables
scope of variables
• Local variables -Variables that are defined inside a
function body have a local scope. local variables can be
accessed only inside the function in which they are
declared
• Global variables -variables those defined outside have
a global scope. global variables can be accessed
throughout the program body by all functions.
• whereas When we call a function, the variables
declared inside it are brought into scope
• def print_twice(part1, part2):
cat = part1 + part2
print_twice(cat)
total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2;
# Here total is local variable.
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
Stack Diagrams
• We must know the variable references that
occurs in code block. To keep track of which
variables can be used where ,it is sometimes
useful to draw a stack diagram.
• Stack diagrams show the value of each variable,
but they also show the function each variable
belongs to.
• Each function is represented by a frame. A frame
is a box with the name of a function beside it and
the parameters and variables of the function
inside it.
• Example:-
• def avrg(n1,n2,n3):
• sum=n1+n2+n3
• avg=sum/3
• print(avg)
• s=11 s->11
t->27
<module>
• t=27 v->8
n1->11

• v=8 n2->27
n3->8
avrg
• avrg(s,t,v) sum->46
avg->15.33
Fruitful functions and Void functions
• The fruitful functions can be referred as the
functions that returns the value. Many of the
math built in functions yield results which are
easy to use.
• Some functions perform an action but don’t
return a value .They are called as void
functions.
Why functions
• • Creating a new function gives you an opportunity to
name a group of statements, which makes your
program easier to read and debug.
• • Functions can make a program smaller by
eliminating repetitive code. Later, if you make a
change, you only have to make it in one place.
• • Dividing a long program into functions allows you to
debug the parts one at a time and then assemble them
into a working whole.
• • Well-designed functions are often useful for many
programs. Once you write and debug one, you can
reuse it.
Importing with from
• Many built in libraries ,modules and packages are provided
by python to support easy programming. These all libraries
we can use in the code by using import statement.
• When the interpreter encounters an import statement ,it
imports the module ,if the module is present in the search
path.
• There are three ways to use import statement in python:-
1) Import statement
• Syntax:-
• import m1[,m2….mN]
• e.g. import math
• print (math.sqrt(4))
2) from….import statement
• It is used to import specific attributes from a
module.
• Syntax:-from mname import nm1[,nm2…..,nmN]
• e.g. from math import pi
• print(pi)
3) from ….import *
• It is used to import all items from a module.
• Syntax:-from mname import *
• e.g from math import *
• print(pi)
• print(sqrt(4))
Incremental development
• As you write larger functions, you might find yourself
spending more time debugging.
• To deal with increasingly complex programs, you might
want to try a process called incremental development.
The goal of incremental development is to avoid long
debugging sessions by adding and testing only a small
amount of code at a time.
• suppose you want to find the distance between two
points, given by the coordinates (x1, y1) and (x2, y2). By
the Pythagorean theorem, the distance is:

√ (x2 − x1)2 + (y2 − y1)2


distance =
• The first step is to consider what a distance function should
look like in Python
• def distance(x1, y1, x2, y2):
return 0.0
this version doesn’t compute distances; it always returns zero. But
it is syntactically correct, and it runs, which means that you can
test it before you make it more complicated.
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
print ('dx is', dx)
print ('dy is', dy )
return 0.0
Boolean Functions
• The result of Boolean function is either True or False.The
function can certainly work with any type of data as
parameter or local variable ,but the result is bool.
• This result can only be assigned to Boolean variable.
• def xyz(s,t):
• if s%t ==0:
• result=True
• else:
• result =False
• return result
• print(xyz(4,2))
More recursion
• A recursive definition is similar to a circular
definition, in the sense that the definition
contains a reference to the thing being defined.
• def factorial(n):
if n == 0:
return 1
else:
recurse = factorial(n-1)
result = n * recurse
return result
Leap of faith
• Following the flow of execution is one way to
read programs, but it can quickly become
labyrinthine. An alternative is what I call the
“leap of faith.” When you come to a function
call, instead of following the flow of execution,
you assume that the function works correctly
and returns the right result.
Checking types
• We can use the built-in function isinstance to verify the type of the
argument. While we’re at it, we can also make sure the argument is
positive:
• def factorial (n):
• if not isinstance(n, int):
• print 'Factorial is only defined for integers.'
• return None
• elif n < 0:
• print 'Factorial is only defined for positive integers.'
• return None
• elif n == 0:
• return 1
• else:
• return n * factorial(n-1)
Strings
• A string is a sequence of characters. Python does
not have a character data type, a single character
is simply a string with a length of 1
• You can access the characters one at a time with
the bracket operator:
• >>> fruit = 'banana'
• >>> letter = fruit[1]
• The second statement selects character number 1
from fruit and assigns it to letter.
• The expression in brackets is called an index.
• len is a built-in function that returns the
number of characters in a string:
• >>> fruit = 'banana'
• >>> len(fruit)
• 6
String Slices
• The "slice" syntax is a handy way to refer to sub-parts
of sequences -- typically strings and lists. The slice
s[start:end] is the elements beginning at start and
extending up to but not including end.
• Selecting a slice is similar to selecting a character:
• >>> s = 'Monty Python'
• >>> s[0:5]
• 'Monty'
• >>> s[6:12]
• 'Python'
• The operator [n:m] returns the part of the string from
the “n-eth” character to the “m-eth” character,
including the first but excluding the last.
• >>> fruit = 'banana'
• >>> fruit[:3]
o/p ban
• >>> fruit[3:]
o/p 'ana'
s = "Hello“
• s[1:4] is 'ell'
• s[1:] is 'ello'
• s[:] is 'Hello'
• s[1:100] is 'ello'
• Python uses negative numbers to give easy access
to the chars at the end of the string:
• s[-1] is the last char 'o',
• s[-2] is 'l' the next-to-last char, and so on.
• Negative index numbers count back from the end
of the string:
• s[-4] is 'e'
• s[:-3] is 'He'
• s[-3:] is 'llo'
Strings Are Immutable
• The [] operator is used on the left side of an
assignment, with the intention of changing a
character in a string. For example
• >>> greeting = 'Hello, world!'
• >>> greeting[0] = 'J' # not allowed
• strings are immutable, which means you can’t
change an existing string.
• >>> greeting = 'Hello, world!‘
• >>> new_greeting = 'J' + greeting[1:]
• >>> new_greeting
• 'Jello, world!'
Traversal with a for/while loop
• A lot of computations involve processing a string one character
at a time. Often they start at the beginning, select each
character in turn, do something to it, and continue until the
end. This pattern of processing is called a traversal
• One way to write a traversal is with a while loop:
index = 0
fruit=‘banana’
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
OR
for letter in fruit:
print(letter)
Searching
• The pattern of computation—traversing a sequence and
returning when we find what we are looking for—is
called a search.
• def find(word, letter):
index = 0
while index < len(word):
if word[index] == letter:
return index
index = index + 1
return -1
Function takes a character and finds the index where that
character appears. If the character is not found, the
function returns -1.
Looping and Counting
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print(count)
String Methods
• s.lower(), s.upper() -- returns the lowercase or
uppercase version of the string
• s.strip() -- returns a string with whitespace removed
from the start and end
• s.isalpha()/s.isdigit()/s.isspace()... -- tests if all the string
chars are in the various character classes
• s.startswith('other'), s.endswith('other') -- tests if the
string starts or ends with the given other string
• s.find('other') -- searches for the given other string (not
a regular expression) within s, and returns the first
index where it begins or -1 if not found
• s.replace('old', 'new') -- returns a string where all
occurrences of 'old' have been replaced by 'new'
• s.split('delim') -- returns a list of substrings separated
by the given delimiter. The delimiter is not a regular
expression, it's just text. 'aaa,bbb,ccc'.split(',') -> ['aaa',
'bbb', 'ccc']. As a convenient special case s.split() (with
no arguments) splits on all whitespace chars.
• s.join(list) -- opposite of split(), joins the elements in
the given list together using the string as the delimiter.
e.g. '---'.join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc
• max( x, y, z, .... )
Returns the largest of its arguments
• min( x, y, z, .... )
Returns the smallest of its arguments
• round( x , n )
returns x rounded to n digits from the decimal
point.
The in Operator
• The word in is a boolean operator that takes
two strings and returns True if the first
appears as a substring in the second:
• >>> 'a' in 'banana'
• True
• >>> 'seed' in 'banana'
• False
String Comparison
• The relational operators work on strings. To see if two
strings are equal:
• if word == 'banana':
print('All right, bananas.')
All the uppercase letters come before all the lowercase letters
if word < 'banana':
print('Your word, ' + word + ', comes before banana.')
elif word > 'banana':
print('Your word, ' + word + ', comes after banana.')
else:
print('All right, bananas.')
String Operations
• str = 'Hello World!'
• print (str) # Prints complete string
• print (str[0]) # Prints first character of the string
• print (str[2:5]) # Prints characters starting from
3rd to 5th
• print (str[2:]) # Prints string starting from 3rd
character
• print (str * 2) # Prints string two times
• print (str + "TEST") # Prints concatenated string

You might also like