Nothing Special   »   [go: up one dir, main page]

Unit-2 Functions (E-Next - In)

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

UNIT 2

FUNCTIONS :

2.1 Composing Expressions

So far, we have looked at the elements of a program—variables, expressions, and


statements —in isolation, without talking about how to combine them. One of the
most useful features of programming languages is their ability to take small building
blocks and compose them. For example, we know how to add numbers and we know
how to print; it turns out we can do both at the same time:

>>> print(17 + 3)
20

In reality, the addition has to happen before the printing, so the actions aren’t
actually happening at the same time. The point is that any expression involving
numbers, strings, and variables can follow print:

>>> hour = 21
>>> minute = 1
>>> print("Number of minutes since midnight: ",hour * 60 + minute)
Number of minutes since midnight: 1261

You can also put arbitrary expressions on the right-hand side of an assignment
statement:

>>> percentage = (minute * 100) / 60


>>> percentage
1.6666666666666667
>>> print(percentage)
1.6666666666666667

This ability may not seem impressive now, but you will see other examples where
the composition makes it possible to express complex computations neatly and
concisely.
Warning: There are limits on where you can use certain expressions. For example,
left-hand side of an assignment statement has to be a variable name, not an
expression. So, the following is illegal:

>>> minute+1 = hour


File "<stdin>", line 1
SyntaxError: can't assign to operator

3.2 Function calls

Many common tasks come up time and time again when programming. Instead of
requiring you to constantly reinvent the wheel, Python has a number of built-in
features which you can use. Including so much ready to use code is sometimes

40

https://E-next.in
referred to as a ’batteries included’ philosophy. Python comes with just under fifty
(of which we’ll be only using about a dozen) and the simplest way to use this
prewritten code is via function calls.

The syntax of a function call is simply


FUNCTION NAME(ARGUMENTS)

Not all functions take an argument, and some take more than one (in which case the
arguments are separated by commas).
You have already seen an example of a function call:

>>> type("Hello,World")
<class 'str'>
>>> type(17)
<class 'int'>
The name of the function is type, and it displays the type of a value or variable. The
value or variable, which is called the argument of the function, has to be enclosed in
parentheses. It is common to say that a function “takes” an argument and “returns” a
result. The result is called the return value.

We can assign the return value to a variable:

>>> result = type(17)


>>> print(result)
<class 'int'>

Another useful function is len. It takes a Python sequence as an argument. The only
Python sequence we have met so far is a string. A string is a sequence of characters.
For a string argument, len returns the number of characters the string contains.

>>> my_str = "Hello world"


>>> len(my_str)
11

The len function can only be used on sequences. Trying to use it on a number, for
example, results in an error.

>>> len(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()

2.3 Type Conversion Functions :

Each Python type comes with a built-in function that attempts to convert values of
another type into that type. The int(ARGUMENT) function, for example, takes any
value and converts it to an integer, if possible, or complains otherwise:

>>> int("32")

41

https://E-next.in
32
>>> int("Hello")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Hello'

The int function can also convert floating-point values to integers, but note that it
truncates the fractional part:

>>> int(-2.3)
-2
>>> int(3.99999)
3
>>> int("42")
42
>>> int(1.0)
1

The float(ARGUMENT) function converts integers and strings to floating-point


numbers:

>>> float(32)
32.0
>>> float("3.14159")
3.14159
>>> float(1)
1.0
It may seem odd that Python distinguishes the integer value 1 from the floating-point
value 1.0. They may represent the same number, but they belong to different types as
they are represented differently inside the computer.

The str(ARGUMENT) function converts any argument to type string:

>>> str(32)
'32'
>>> str(3.14149)
'3.14149'
>>> str(True)
'True'
>>> str(true)
Traceback (most recent call last): File
"<stdin>", line 1, in <module>
NameError: name 'true' is not defined

The str(ARGUMENT) function will work with any value and convert it into a string.
Note: True is a predefined value in Python; true is not.

2.4 Math Functions :

Python includes following functions that perform mathematical calculations.

42

https://E-next.in
Function Returns ( description )

abs(x) The absolute value of x: the (positive) distance between x and zero.

ceil(x) The ceiling of x: the smallest integer not less than x

cmp(x, y) -1 if x < y, 0 if x == y, or 1 if x > y

exp(x) The exponential of x: ex

fabs(x) The absolute value of x.

floor(x) The floor of x: the largest integer not greater than x

log(x) The natural logarithm of x, for x> 0

log10(x) The base-10 logarithm of x for x> 0.

max(x1, x2,...) The largest of its arguments: the value closest to positive infinity

min(x1, x2,...) The smallest of its arguments: the value closest to negative infinity

The fractional and integer parts of x in a two-item tuple. Both


modf(x) parts have the same sign as x. The integer part is returned as a
float.
pow(x, y) The value of x**y.

x rounded to n digits from the decimal point. Python rounds away


round(x [,n]) from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.

Number abs() Method :


Description: The abs() method returns the absolute value of x i.e. the positive distance
between x and zero.
Syntax : Following is the syntax for abs() method-
abs(x)
Parameters :
x - This is a numeric expression.
Return : This method returns the absolute value of x.
The following example shows the usage of the abs() method.

print ("abs(-45) : ", abs(-45))


print ("abs(100.12) : ", abs(100.12))

43

https://E-next.in
When we run the above program, it produces the following result-

abs(-45): 45
abs(100.12) : 100.12

Number ceil() Method :


Description: The ceil() method returns the ceiling value of x i.e. the smallest integer
not less than x.
Syntax: Following is the syntax for the ceil() method
import math
math.ceil( x )
Note: This function is not accessible directly, so we need to import math module and
then we need to call this function using the math static object.

Parameters
x - This is a numeric expression.
Return Value
This method returns the smallest integer not less than x.
Example
The following example shows the usage of the ceil() method.

import math # This will import math module


print ("math.ceil(-45.17) : ", math.ceil(-45.17))
print ("math.ceil(100.12) : ", math.ceil(100.12))
print ("math.ceil(100.72) : ", math.ceil(100.72))
print ("math.ceil(math.pi) : ", math.ceil(math.pi))

When we run the above program, it produces the following result

math.ceil(-45.17) : -45
math.ceil(100.12) : 101
math.ceil(100.72) : 101
math.ceil(math.pi) : 4

Number exp() Method


Description
The exp() method returns exponential of x: ex.
Syntax
Following is the syntax for the exp() method

import math
math.exp( x )

Note: This function is not accessible directly. Therefore, we need to import the math
module and then we need to call this function using the math static object.
Parameters
X - This is a numeric expression.
Return Value
This method returns exponential of x: ex.

44

https://E-next.in
Example
The following example shows the usage of exp() method.

import math # This will import math module


print ("math.exp(-45.17) : ", math.exp(-45.17))
print ("math.exp(100.12) : ", math.exp(100.12))
print ("math.exp(100.72) : ", math.exp(100.72))
print ("math.exp(math.pi) : ", math.exp(math.pi))

When we run the above program, it produces the following result

math.exp(-45.17) : 2.4150062132629406e-20
math.exp(100.12) : 3.0308436140742566e+43
math.exp(100.72) : 5.522557130248187e+43
math.exp(math.pi) : 23.140692632779267

Number fabs() Method


Description
The fabs() method returns the absolute value of x. Although similar to the abs()
function, there are differences between the two functions. They are-
• abs() is a built in function whereas fabs() is defined in math module.
• fabs() function works only on float and integer whereas abs() works with
complex number also.
Syntax
Following is the syntax for the fabs() method

import math
math.fabs( x )

Note: This function is not accessible directly, so we need to import the math module
and
then we need to call this function using the math static object.

Parameters
x - This is a numeric value.
Return Value
This method returns the absolute value of x.
Example
The following example shows the usage of the fabs() method.

import math # This will import math module


print ("math.fabs(-45.17) : ", math.fabs(-45.17))
print ("math.fabs(100.12) : ", math.fabs(100.12))
print ("math.fabs(100.72) : ", math.fabs(100.72))
print ("math.fabs(math.pi) : ", math.fabs(math.pi))

When we run the above program, it produces following result

math.fabs(-45.17) : 45.17

45

https://E-next.in
math.fabs(100.12) : 100.12
math.fabs(100.72) : 100.72
math.fabs(math.pi) : 3.141592653589793

Number floor() Method


Description
The floor() method returns the floor of x i.e. the largest integer not greater than x.
Syntax
Following is the syntax for the floor() method

import math
math.floor( x )

Note: This function is not accessible directly, so we need to import the math module
and then we need to call this function using the math static object.
Parameters
x - This is a numeric expression.
Return Value
This method returns the largest integer not greater than x.
The following example shows the usage of the floor() method.

import math # This will import math module


print ("math.floor(-45.17) : ", math.floor(-45.17))
print ("math.floor(100.12) : ", math.floor(100.12))
print ("math.floor(100.72) : ", math.floor(100.72))
print ("math.floor(math.pi) : ", math.floor(math.pi))

When we run the above program, it produces the following result

math.floor(-45.17) : -46
math.floor(100.12) : 100
math.floor(100.72) : 100
math.floor(math.pi) : 3

Number log() Method


Description
The log() method returns the natural logarithm of x, for x > 0.
Syntax
Following is the syntax for the log() method

import math
math.log( x )

Note: This function is not accessible directly, so we need to import the math module
and then we need to call this function using the math static object.

Parameters

46

https://E-next.in
x - This is a numeric expression.
Return Value
This method returns natural logarithm of x, for x > 0.
Example
The following example shows the usage of the log() method.

import math # This will import math module


print ("math.log(100.12) : ", math.log(100.12))
print ("math.log(100.72) : ", math.log(100.72))
print ("math.log(math.pi) : ", math.log(math.pi))

When we run the above program, it produces the following result

math.log(100.12) : 4.6063694665635735
math.log(100.72) : 4.612344389736092
math.log(math.pi) : 1.1447298858494002

Number log10() Method


Description
The log10() method returns base-10 logarithm of x for x > 0.
Syntax
Following is the syntax for log10() method

import math
math.log10( x )

Note: This function is not accessible directly, so we need to import the math module
and then we need to call this function using the math static object.

Parameters
x - This is a numeric expression.
Return Value
This method returns the base-10 logarithm of x for x > 0.
Example
The following example shows the usage of the log10() method.

import math # This will import math module


print ("math.log10(100.12) : ", math.log10(100.12))
print ("math.log10(100.72) : ", math.log10(100.72))
print ("math.log10(119) : ", math.log10(119))
print ("math.log10(math.pi) : ", math.log10(math.pi))
When we run the above program, it produces the following result

math.log10(100.12) : 2.0005208409361854
math.log10(100.72) : 2.003115717099806
math.log10(119) : 2.0755469613925306
math.log10(math.pi) : 0.49714987269413385

Number max() Method


Description

47

https://E-next.in
The max() method returns the largest of its arguments i.e. the value closest to positive
infinity.
Syntax
Following is the syntax for max() method

max(x, y, z, .... )

Parameters
• x - This is a numeric expression.
• y - This is also a numeric expression.
• z - This is also a numeric expression.
Return Value
This method returns the largest of its arguments.
Example
The following example shows the usage of the max() method.

print ("max(80, 100, 1000) : ", max(80, 100, 1000))


print ("max(-20, 100, 400) : ", max(-20, 100, 400))
print ("max(-80, -20, -10) : ", max(-80, -20, -10))
print ("max(0, 100, -400) : ", max(0, 100, -400))

When we run the above program, it produces the following result

max(
80, 100, 1000) : 1000
max(-20, 100, 400) : 400
max(-80, -20, -10) : -10
max(0, 100, -400) : 100

Number min() Method


Description
The method min() returns the smallest of its arguments i.e. the value closest to
negative
infinity.
Syntax
Following is the syntax for the min() method

min(x, y, z, .... )

Parameters
• x - This is a numeric expression.
• y - This is also a numeric expression.
• z - This is also a numeric expression.
Return Value
This method returns the smallest of its arguments.
Example
The following example shows the usage of the min() method.

print ("min(80, 100, 1000) : ", min(80, 100, 1000))

48

https://E-next.in
print ("min(-20, 100, 400) : ", min(-20, 100, 400))
print ("min(-80, -20, -10) : ", min(-80, -20, -10))
print ("min(0, 100, -400) : ", min(0, 100, -400))

When we run the above program, it produces the following result

min(80, 100, 1000) : 80


min(-20, 100, 400) : -20
min(-80, -20, -10) : -80
min(0, 100, -400) : -400

Number modf() Method


Description
The modf() method returns the fractional and integer parts of x in a two-item tuple.
Both parts have the same sign as x. The integer part is returned as a float.
Syntax
Following is the syntax for the modf() method

import math
math.modf( x )

Note: This function is not accessible directly, so we need to import the math module
and then we need to call this function using the math static object.

Parameters
x - This is a numeric expression.
Return Value
This method returns the fractional and integer parts of x in a two-item tuple. Both the
parts have the same sign as x. The integer part is returned as a float.
Example
The following example shows the usage of the modf() method.

import math # This will import math module


print ("math.modf(100.12) : ", math.modf(100.12))
print ("math.modf(100.72) : ", math.modf(100.72))
print ("math.modf(119) : ", math.modf(119))
print ("math.modf(math.pi) : ", math.modf(math.pi))

When we run the above program, it produces the following result

math.modf(100.12) : (0.12000000000000455, 100.0)


math.modf(100.72) : (0.7199999999999989, 100.0)
math.modf(119) : (0.0, 119.0)
math.modf(math.pi) : (0.14159265358979312, 3.0)

Number pow() Method


Return Value
This method returns the value of xy.
Example
The following example shows the usage of the pow() method.

49

https://E-next.in
import math # This will import math module
print ("math.pow(100, 2) : ", math.pow(100, 2))
print ("math.pow(100, -2) : ", math.pow(100, -2))
print ("math.pow(2, 4) : ", math.pow(2, 4))
print ("math.pow(3, 0) : ", math.pow(3, 0))

When we run the above program, it produces the following result

math.
pow(100, 2) : 10000.0
math.pow(100, -2) : 0.0001
math.pow(2, 4) : 16.0
math.pow(3, 0) : 1.0

Number round() Method


Description
round() is a built-in function in Python. It returns x rounded to n digits from the
decimal point.
Syntax
Following is the syntax for the round() method

round(x [, n] )

Parameters
• x - This is a numeric expression.
• n - Represents number of digits from decimal point up to which x is to be
rounded.
Default is 0.
Return Value
This method returns x rounded to n digits from the decimal point.
Example
The following example shows the usage of round() method

print ("round(70.23456) : ", round(70.23456))


print ("round(56.659,1) : ", round(56.659,1))
print ("round(80.264, 2) : ", round(80.264, 2))
print ("round(100.000056, 3) : ", round(100.000056, 3))
print ("round(-100.000056, 3) : ", round(-100.000056, 3))

When we run the above program, it produces the following result

round(70.23456) : 70
round(56.659,1) : 56.7
round(80.264, 2) : 80.26
round(100.000056, 3) : 100.0
round(-100.000056, 3) : -100.0

Number sqrt() Method


Description

50

https://E-next.in
The sqrt() method returns the square root of x for x > 0.
Syntax
Following is the syntax for sqrt() method

import math
math.sqrt( x )

Note: This function is not accessible directly, so we need to import the math module
and then we need to call this function using the math static object.

Parameters
x - This is a numeric expression.
Return Value
This method returns square root of x for x > 0.
Example
The following example shows the usage of sqrt() method.

import math # This will import math module


print ("math.sqrt(100) : ", math.sqrt(100))
print ("math.sqrt(7) : ", math.sqrt(7))
print ("math.sqrt(math.pi) : ", math.sqrt(math.pi))

When we run the above program, it produces the following result

math.sqrt(100) : 10.0
math.sqrt(7) : 2.6457513110645907
math.sqrt(math.pi) : 1.7724538509055159

2.5 Function Composition :

Just as with mathematical functions, Python functions can be composed, meaning that
you use the result of one function as the input to another.

>>> def print_twice(some_variable_name):


... print(some_variable_name, some_variable_name)
...
>>> print_twice(abs(-7))
77
>>> print_twice(max(3,1,abs(-11),7))
11 11

In the first example, abs(-7) evaluates to 7, which then becomes the argument to
print twice. In the second example we have two levels of composition, since abs(-
11) is first evaluated to 11 before max(3, 1, 11, 7) is evaluated to 11 and (11)
print_twice then displays the result.

We can also use a variable as an argument:

51

https://E-next.in
>>> saying = "Eric,the half a bee."
>>> print_twice(saying)
Eric,the half a bee. Eric,the half a bee.

Notice something very important here. The name of the variable we pass as an
argument (saying) has nothing to do with the name of the parameter
(some_variable_name). It doesn’t matter what the argument is called; here in
print_twice, we call everybody some_variable_name.

2.5 Adding New Functions

A new function can be created in python using keyword def followed by the function
name and arguments in parathesis and statements to be executed in function
Example:
def requiredArg (str,num):
statements
2.6 Function definitions and use

As well as the built-in functions provided by Python you can define your own
functions. In the context of programming, a function is a named sequence of
statements that performs a desired operation. This operation is specified in a function
definition. In Python, the syntax for a function definition is:

def NAME( LIST OF PARAMETERS ):


STATEMENTS

The ’list of parameters’ is where the arguments supplied to the function end up.
You will see more of this later.

You can make up any names you want for the functions you create, except that you
can’t use a name that is a Python keyword. The list of parameters specifies what
information, if any, you have to provide in order to use the new function.

There can be any number of statements inside the function, but they have to be you.
indented from the def. In the examples in this book, we will use the standard
indentation of four spaces3. IDLE automatically indents compound statements for
Function definitions are the first of several compound statements we will see, all
of which have the same pattern:
1. A header, which begins with a keyword and ends with a colon.
2. A body consisting of one or more Python statements, each indented the same
amount – 4 spaces is the Python standard – from the header.

In a function definition, the keyword in the header is def, which is followed by the
list name of the function and a list of parameters enclosed in parentheses. The
parameter may be empty, or it may contain any number of parameters. In either
case, the parentheses are required. The first couple of functions we are going to no
write have parameters, so the syntax looks like this:

52

https://E-next.in
>>> def new_line() :
... print()

This function is named new_line. The empty parentheses indicate that it has no
which parameters (that is it takes no arguments). Its body contains only a single
statement, outputs a newline character. (That’s what happens when you use a print
command without any arguments.)

Defining a new function does not make the function run. To do that we need a by a
function call. Function calls contain the name of the function to be executed
followed list of values, called arguments, which are assigned to the parameters in
the function definition. Our first examples have an empty parameter list, so the do
function calls not take any arguments. Notice, however, that the parentheses are
required in the function call :

... print("First Line.")


... new_line()
... print("Second Line")
The output of the function is :

First Line.

Second Line
The extra space between the two lines is a result of the new line() function call.
What if we wanted more space between the lines? We could call the same function
repeatedly:

... print("First Line.")


... new_line()
... new_line()
... new_line()
... print("Second Line")
Or we could write a new function named three lines that prints three new lines:

>>> def three_lines() :


... new_line()
... new_line()
... new_line()

... print("First Line.")


... three_lines()
... print("Second Line.")

This function contains three statements, all of which are indented by four spaces.
Since the next statement is not indented, Python knows that it is not part of the
function. You should notice a few things about this program:
• You can call the same procedure repeatedly. In fact, it is quite common and
useful to do so.
• You can have one function call another function; in this case three lines calls
new_line.

53

https://E-next.in
So far, it may not be clear why it is worth the trouble to create all of these new
functions. Actually, there are a lot of reasons, but this example demonstrates two:
1. Creating a new function gives you an opportunity to name a group of
statements. Functions can simplify a program by hiding a complex computation
behind a single command and by using English words in place of arcane code.
2. Creating a new function can make a program smaller by eliminating repetitive
code. For example, a short way to print nine consecutive new lines is to call
three lines three times.

Pulling together the code fragments from the previous section into a script named
functions.py, the whole program looks like this:

def new_line() :
print()

def three_lines() :
new_line()
new_line()
new_line()

print("First Line.")
three_lines()
print("Second Line.")

This program contains two function definitions: new_line and three_lines. Function
to definitions get executed just like other statements, but the effect is to create the
new function. The statements inside the function do not get executed until the is
called, and the function definition generates no output. As you might expect, you
have create a function before you can execute it. In other words, the function
definition has to be executed before the first time it is called.

2.7 Flow of Execution

In order to ensure that a function is defined before its first use, you have to know
the order in which statements are executed, which is called the flow of execution.
Execution always begins at the first statement of the program. Statements are
executed 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 are not executed until the function is called. Although it is not common,
you can define one function inside another. In this case, the inner definition isn’t
executed until the outer function is called.

Function calls are like a detour in the flow of execution. Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the
statements there, and then comes back to pick up where it left off. That sounds
simple enough, until you remember that one function can call another. While in the
middle of one function, the program might have to execute the statements in another
function. But while executing that new function, the program might have to execute

54

https://E-next.in
yet another function! Fortunately, Python is adept at keeping track of where it is, so
each time a function completes, the program picks up where it left off in the
function that called it. When it gets to the end of the program, it terminates.

It is usually not helpful to read a program from top to bottom. In python programs
the top part of a file is almost always used for function definitions and it is not
necessary to read those until you want to understand what a particular function
does. The bottom part of a python file is often called the main program. This part
can be recognised because it is often not indented. It is easier to understand a the
program by following flow of execution starting at the beginning of the main
program.

2.8 Parameters and Arguments

Most functions require arguments. Arguments are values that are input to the function
and these contain the data that the function works on. For example, if you want to find
the absolute value of a number (the distance of a number from zero) you have to
indicate what the number is. Python has a built-in function for computing the absolute
value:

>>> abs(5)
5
>>> abs(-5)
5

In this example, the arguments to the abs function are 5 and -5.

Some functions take more than one argument. For example the built-in function pow
takes two arguments, the base and the exponent. Inside the function, the values that are
passed get assigned to variables called parameters.

>>> pow(2,3)
8
>>> pow(3,2)
9

The first argument is raised to the power of the second argument.

round(), not surprisingly, rounds a number and returns the floating point value first is
rounded to n-digits digits after the decimal point. It takes one or two arguments. The
number to be rounded and the second (optional) value is the number of digits to round
to. If the second number is not supplied it is assumed to be zero.

>>> round(1.23456789)
1
>>> round(1.5)
2
>>> round(1.23456789,2)
1.23

55

https://E-next.in
>>> round(1.23456789,3)
1.235

Another built-in function that takes more than one argument is max.

>>> max(7,11)
11
>>> max(1,4,17,2,12)
17
>>> max(3*11, 5**3, 512-9, 1024**0)
503

The function max can be sent any number of arguments, separated by commas, and
will return the maximum value sent. The arguments can be either simple values or
expressions. In the last example, 503 is returned, since it is larger than 33, 125, and 1.
Here is an example of a user-defined function that has a parameter:

>>> def print_twice(some_variable_name):


... print(some_variable_name, some_variable_name)

This function takes a single argument and assigns it to the parameter named will be) is
some_variable_name. The value of the parameter (at this point we have no idea what it
printed twice, followed by a newline. The name some_variable_name was chosen to
suggest that the name you give a parameter is up to you,but in general, you want to
choose something more descriptive than some_variable_name.

In a function call, the value of the argument is assigned to the corresponding parameter
in the function definition. In effect, it is as if some_variable_name = "Spam" is
executed when print_twice("Spam") is called; some_variable_name = 5 is executed
when print_twice(5) is called; and some_variable_name = 3.14159 is executed when
print_twice(3.14159) is called. Any type of argument that can be printed can be sent to
print_twice. In the first function call, the argument is a string. In the second, it’s an
integer. In the third, it’s a float.

As with built-in functions, we can use an expression as an argument for print twice:

>>> print_twice("Spam"*4)
SpamSpamSpamSpam SpamSpamSpamSpam

"Spam"*4 is first evaluated to ’SpamSpamSpamSpam’, which is then passed as an


argument to print_twice.

2.9 Variable and Parameters are Local

>>> def print_joined_twice(part1, part2) :


... joined = part1 + part2
... print_twice(joined)
This function takes two arguments, concatenates them and stores the result in a local
variable joined. It then calls print twice with joined as the argument. print twice prints
the value of the argument, twice. We can call the function with two strings:

56

https://E-next.in
>>> line1 = "Happy birthday,"
>>> line2 = "to you."
>>> print_joined_twice(line1, line2)
Happy birthday,to you. Happy birthday,to you.

When print joined twice terminates, the variable joined is destroyed. If we try to print
it, we get an error:

>>> print(joined)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'joined' is not defined

When you create a local variable inside a function, it only exists inside that function,
and you cannot use it outside. Parameters are also local. For example, outside the
function print_twice, there is no such thing as phrase. If you try to use it, Python will
complain. Similarly, part1 and part2 do not exist outside print_joined_twice.

2.10 Stack Diagrams

To keep track of which variables can be used where, it is sometimes useful to draw a
stack diagram. Like state diagrams, stack diagrams show the value of each variable, but
they also show the function to which each variable belongs. 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. The stack diagram for the previous
example looks like this:

print_twice phrase "Happy birthday, to you."

print_joined_twice part1 "Happy birthday, "


"to you."
part2
joined "Happy birthday, to you."

_main_
line1 "Happy birthday, "
line2 "to you."

The order of the stack shows the flow of execution. print_twice was called by
print_joined_twice, and print_joined_twice was called by _main_ , which is a special
name for the topmost function. When you create a variable outside of any function, it
belongs to _main_ . Each parameter refers to the same value as its corresponding
argument. So, part1 has the same value as line1, part2 has the same value as line2, and
phrase has the same value as joined. If an error occurs during a function call, Python
prints the name of the function, and the name of the function that called it, and the
name of the function that called that, all the way back to the top most function. To see
how this works, we create a Python script named stacktrace.py that looks like this:

57

https://E-next.in
def print_twice(phrase):
print(phrase, phrase)
print(joined)

def print_joined_twice(part1, part2):


joined = part1 + part2
print_twice(joined)

line1 = "Happy birthday, "


line2 = "to you."
print_joined_twice(line1, line2)

We’ve added the statement, print joined inside the print twice function, but joined is
not defined there. Running this script will produce an error message like this:

Traceback (most recent call last):


File "C:/Python34/example.py", line 11, in <module>
print_joined_twice(line1, line2)
File "C:/Python34/example.py", line 7, in print_joined_twice
print_twice(joined)
File "C:/Python34/example.py", line 3, in print_twice
print(joined)
NameError: name 'joined' is not defined

This list of functions is called a traceback. It tells you what program file the error
occurred in, and what line, and what functions were executing at the time. It also shows
the line of code that caused the error. Notice the similarity between the traceback and
the stack diagram. It’s not a coincidence. In fact, another common name for a traceback
is a stack trace.

2.11 Fruitful functions and Void functions

2.11.1 The return statement


The return statement allows you to terminate the execution of a function before
you reach the end. One reason to use it is if you detect an error condition:

def print_square_root(x):
if x < 0:
print("Warning: cannot take square root of a negative number.")
return
result = x**0.5
print("The square root of x is", result)

The function print square root has a parameter named x. The first thing it does is check
whether x is less than 0, in which case it displays an error message and then uses return
to exit the function. The flow of execution immediately returns to the caller, and the
remaining lines of the function are not executed.

58

https://E-next.in
2.11.2 Return values
The built-in functions we have used, such as abs, pow, round and max, have produced
results. Calling each of these functions generates a value, which we usually assign to a
variable or use as part of an expression.

biggest = max(3, 7, 2, 5)
x = abs(3 - 11) + 10

So far, none of the functions we have written has returned a value, they have printed
values. In this lecture, we are going to write functions that return values, which we will
call fruitful functions, for want of a better name. The first example is area_of_circle,
which returns the area of a circle with the given radius:

def area_of_circle(radius):
if radius < 0:
print("Warning: radius must be non-negative")
return
area = 3.14159 * radius**2
return area

We have seen the return statement before, but in a fruitful function the return statement
includes a return value. This statement means: Return immediately from this function
and use the following expression as a return value. The expression provided can be
arbitrarily complicated, so we could have written this function more concisely:

def area_of_circle(radius):
if radius < 0:
print("Warning: radius must be non-negative")
return
return 3.14159 * radius**2

On the other hand, temporary variables like area often make debugging easier.
Sometimes it is useful to have multiple return statements, one in each branch of a
conditional. For instance, we have already seen the built-in abs, now we see how to
write our own:

def absolute_value(x):
if x < 0:
return -x
else:
return x

Since these return statements are in an alternative conditional, only one will be
executed. As soon as one is executed, the function terminates without executing any
subsequent statements. Another way to write the above function is to leave out the else
and just follow if the condition by the second return statement.

def absolute_value(x):
if x < 0:
return -x

59

https://E-next.in
return x

Think about this version and convince yourself it works the same as the first one. Code
that appears any place the flow of execution can never reach, is called dead code. In a
fruitful function, it is a good idea to ensure that every possible path through the
program hits a return statement. The following version of absolute value fails to do
this:

def absolute_value(x):
if x < 0:
return -x
elif x > 0:
return x

This version is not correct because if x happens to be 0, neither condition is true, and
the function ends without hitting a return statement. In this case, the return value is a
special value called None:

>>> print(absolute_value(0))
None

None is the unique value of a type called the NoneType:

>>> type(None)
<class 'NoneType'>

All Python functions return None whenever they do not return another value. So the
earlier functions we wrote that didn’t have a return statement were actually returning
values, we just never checked.

>>> def print_hello() :


print("hello")

>>> return_value = print_hello()


hello
>>> type(return_value)
<class 'NoneType'>

2.11.3 Program Development

At this point, you should be able to look at complete functions and tell what they do.
Also, while completing the laboratory exercises given so far, you will have written
some small functions. As you write larger functions, you might start to have more
difficulty, especially with runtime and semantic errors. To deal with increasingly
complex programs, we are going to suggest a technique 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.

60

https://E-next.in
As an example, 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:

(𝑥𝑥𝑥𝑥2 − 𝑥𝑥𝑥𝑥1)2 + (𝑦𝑦𝑦𝑦2 − 𝑦𝑦𝑦𝑦1)2


distance =�

The first step is to consider what a distance function should look like in Python. In
other words, what are the inputs (parameters) and what is the output (return value)? In
this case, the two points are the inputs, which we can represent using four parameters.
The return value is the distance, which is a floating-point value. Already we can write
an outline of the function:

def distance(x1, y1, x2, y2):


return 0.0

Obviously, this version of the function doesn’t compute distances; it always returns
zero. But it is syntactically correct, and it will run, which means that we can test it
before we make it more complicated. To test the new function, we call it with sample
values:

>>> distance(1,2,4,6)
0.0

We chose these values so that the horizontal distance equals 3 and the vertical distance
equals 4; that way, the result is 5 (the hypotenuse of a 3-4-5 triangle). When testing a
function, it is useful to know the right answer. At this point we have confirmed that the
function is syntactically correct, and we can start adding lines of code. After each
incremental change, we test the function again. If an error occurs at any point, we
know where it must be—in the last line we added.

A logical first step in the computation is to find the differences x2 − x1 and y2 − y1.
We will store those values in temporary variables named dx and dy and print them.

def distance(x1, y1, x2, y2):


dx = x2 - x1
dy = y2 - y1
print("dx is", dx)
print("dy is", dy)
return 0.0

If the function is working, the outputs should be 3 and 4. If so, we know that the
function is getting the right parameters and performing the first computation correctly.
If not, there are only a few lines to check.

Next we compute the sum of squares of dx and dy:

def distance(x1, y1, x2, y2):


dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
print("dsquared is: ", dsquared)

61

https://E-next.in
return 0.0

Notice that we removed the print statements we wrote in the previous step. Code like
that is called scaffolding because it is helpful for building the program but is not part of
the final product. Again, we would run the program at this stage and check the output
(which should be 25). Finally, using the fractional exponent 0.5 to find the square root,
we compute and return the result:

def distance(x1, y1, x2, y2):


dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = dsquared**0.5
return result

If that works correctly, you are done. Otherwise, you might want to print the value of
result before the return statement. When you start out, you should add only a line or
two of code at a time. As you gain more experience, you might find yourself writing
and debugging bigger chunks. Either way, the incremental development process can
save you a lot of debugging time. The key aspects of the process are:
1. Start with a working program and make small incremental changes. At any
point, if there is an error, you will know exactly where it is.
2. Use temporary variables to hold intermediate values so you can output and
check them.
3. Once the program is working, you might want to remove some of the
scaffolding or consolidate multiple statements into compound expressions, but
only if it does not make the program difficult to read.

2.11.4 Composition

As you should expect by now, you can call one function from within another. This
ability is called composition. As an example, we’ll write a function that takes two
points, the center of the circle and a point on the perimeter, and computes the area of
the circle. Assume that the center point is stored in the variables xc and yc, and the
perimeter point is in xp and yp. The first step is to find the radius of the circle, which is
the distance between the two points. Fortunately, we’ve just written a function,
distance, that does just that, so now all we have to do is use it:

radius = distance(xc, yc, xp, yp)

The second step is to find the area of a circle with that radius and return it. Again we
will use one of our earlier functions:

result = area_of_circle(radius)

Wrapping that up in a function, we get:

def area_of_circle_two_points(xc, yc, xp, yp):


radius = distance(xc, yc, xp, yp)
result = area_of_circle(radius)

62

https://E-next.in
return result

We called this function area of circle two points to distinguish it from the
area_of_circle function defined earlier. There can only be one function with a given
name within a given module. The temporary variables radius and result are useful for
development and debugging, but once the program is working, we can make it more
concise by composing the function calls:

def area_of_circle_two_points(xc, yc, xp, yp):


return area_of_circle(distance(xc, yc, xp, yp))

2.11.5 Boolean functions

Functions can return boolean values, which is often convenient for hiding complicated
tests inside functions. For example:

>>> def is_divisible(x, y):


if x % y == 0:
return True
else:
return False

The name of this function is is divisible. It is common to give boolean functions names
that sound like yes/no questions. is_divisible returns either True or False to indicate
whether the x is or is not divisible by y. We can make the function more concise by
taking advantage of the fact that the condition of the if statement is itself a boolean
expression. We can return it directly, avoiding the if statement altogether:

def is_divisible(x, y):


return x % y == 0

This session shows the new function in action:

>>> is_divisible(6,4)
False
>>> is_divisible(6,3)
True

Boolean functions are often used in conditional statements:

if is_divisible(x, y):
print("x is divisible by y")
else:
print("x is not divisible by y")

It might be tempting to write something like:

if is_divisible(x, y) == True:
print("x is divisible by y")

63

https://E-next.in
else:
print("x is not divisible by y")

But the extra comparison is unnecessary.

2.11.6 Void Functions

Void functions are functions, like ‘print_twice’ (that we defined earlier), that perform
an action (either display something on the screen or perform some other action).
However, they do not return a value.
For instance, we defined the function ‘print_twice’. The function is meant to perform
the action of printing twice the parameter ‘bruce’.

In interactive mode:Python will display the result of a void function if and only if we
call a function in interactive mode.
In script mode:When we call a fruitful function all by itself in script mode, the return
value is lost forever if we do not store or display the result.
For instance:

>>> def print_twice(some_variable):


… print(some_variable)
… print(some_variable)

>>> result = print_twice(‘Bing’)
Bing
Bing
>>> print result
None

It is important to note that although Python displayed the value of result earlier, the
result displayed:
Bing
Bing
is lost forever since we did not store it anywhere.
In order to transmit this idea Python created the notion of ‘None’. It is a special value
that has its own type.

>>> print(type(None))
<class 'NoneType'>

2.12 Importing with from


We can use functions in modules in three different ways:

 Import a module object in Python:If you import math, you get a module object
named math. The module object contains constants like pi and functions like sin
and exp.

64

https://E-next.in
>>> import math

>>> print(math)

<module 'math' (built-in)>

>>> print(math.pi)

3.141592653589793

 Import an object from a module in Python

>>> print(math.pi)
3.141592653589793

Now you can access pi directly, without dot notation.

>>> print(pi)

3.141592653589793

 Import all objects from a module in Python

>>> from math import*

The advantage of importing everything from the math module is that your code can be
more concise. The disadvantage is that there might be conflicts between names defined
in different modules, or between a name from a module and one of your variables.

2.13 More Recursion

Recursion is a way of programming or coding a problem, in which a function calls


itself one or more times in its body. Usually, it is returning the return value of this
function call. If a function definition fulfils the condition of recursion, we call this
function a recursive function.

Termination condition:
A recursive function has to terminate to be used in a program. A recursive function
terminates, if with every recursive call the solution of the problem is downsized and
moves towards a base case. A base case is a case, where the problem can be solved
without further recursion. A recursion can lead to an infinite loop, if the base case is

65

https://E-next.in
not met in the calls.

Example:

4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1

Replacing the calculated values gives us the following expression


4! = 4 * 3 * 2 * 1

Generally we can say: Recursion in computer science is a method where the solution to
a problem is based on solving smaller instances of the same problem.

Recursion functions in Python


Now we come to implement the factorial in Python. It's as easy and elegant as the
mathematical definition.

def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

We can track how the function works by adding two print() functions to the previous
function definition:

def factorial(n):
print("factorial has been called with n = " + str(n))
if n == 1:
return 1
else:
res = n * factorial(n-1)
print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)
return res

>>> print(factorial(5))

This Python script outputs the following results:

factorial has been called with n = 5


factorial has been called with n = 4
factorial has been called with n = 3
factorial has been called with n = 2
factorial has been called with n = 1
intermediate result for 2 * factorial( 1 ): 2
intermediate result for 3 * factorial( 2 ): 6
intermediate result for 4 * factorial( 3 ): 24
intermediate result for 5 * factorial( 4 ): 120

66

https://E-next.in
120

2.13 Leap of Faith


Trust in the code blocks you created and tested.

2.14 Checking Types

The built-in function isinstance is introduced in this section. The function verifies the
type of argument.
On section 2.13, we developed a function called factorial. Let us take another step
further and check the type of the argument and make sure it is positive.

def factorial(n) :
if not isinstance(n,int) :
print("Factorial is only defined for intergers.")
return None;
elif n<0 :
print("Factorial is not defined for negative intergers.")
return None;
elif n == 0 :
return 1;
else :
return n * factorial(n-1)

>>> factorial('banana')
Factorial is only defined for intergers.
>>> factorial(3.5)
Factorial is only defined for intergers.
>>> factorial(-1)
Factorial is not defined for negative intergers.
>>> factorial(8)
40320

This program demonstrates a pattern sometimes called a guardian. The first two
conditionals act as guardians [(not isinstance) and (elif n < 0)] , protecting the code
that follows from values that might cause an error.
The guardians make it possible to prove the correctness of the code.

STRINGS

2.15 A String Is A sequence of Characters

Strings in Python are identified as a contiguous set of characters represented in the


quotation marks. Python allows either pair of single or double quotes. Subsets of
strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0 in the
beginning of the string and working their way from -1 to the end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the

67

https://E-next.in
repetition operator. For example-

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

This will produce the following result

Hello World!
H
Llo
llo World!
Hello World!Hello World!
Hello World!TEST

2.16 Traversal as a For Loop

Recall we said that all programming languages allowed you to perform a few basic
operations: get input, display output, do math, do conditional execution and then there
was just one more thing. The last thing we need to add to the list is repetition, the
ability to loop through a set of statements repeatedly. We will look at this in a lot more
detail later but there is a special type of loop that is particularly useful with strings (and
other compound types) which is worth introducing while we are looking at strings.

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. Python provides a very
useful language feature for traversing many compound types— the for loop:

>>> fruit ='banana'


>>> for char in fruit:
print(char)

The above piece of code can be understood as an abbreviated version of an English


sentence: “For each character in the string fruit, print out the character”. The for loop is
an example of an iterator: something that visits or selects every element in a structure
(in this case a string), usually in turn. The for loop also works on other compound types
such as lists and tuples, which we will look at later.

The following example shows how to use concatenation and a for loop to generate an
abecedarian series. Abecedarian refers to a series or list in which the elements appear
in alphabetical order. For example, in Robert McCloskey’s book Make Way for
Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack,
Pack, and Quack. This loop outputs these names in order:

prefixes = "JKLMNOPQ"

68

https://E-next.in
suffix = "ack"
for letter in prefixes:
print letter + suffix

The output of this program is:

Jack
Kack
Lack
Mack
Nack
Nack
Oack
Pack
Qack

2.17 String Slices

A substring of a string is called a slice. Selecting a slice is similar to selecting a


character:

>>> s = "Peter, Paul, and Mary"


>>> print(s[0:5])
Peter
>>> print(s[7:11])
Paul
>>> print(s[17:21])
Mary

The operator [n:m] returns the part of the string from the nth character to the mth
character, including the first but excluding the last. If you find this behaviour
counterintuitive it might make more sense if you imagine the indices pointing between
the characters, as in the following diagram:

fruit ’ banana’
index 0 1 2 3 4 5 6

If you omit the first index (before the colon), the slice starts at the beginning of the
string. If you omit the second index, the slice goes to the end of the string. Thus:

>>> fruit= "banana"


>>> fruit[0:3]
'ban'
>>> fruit[3:]
'ana'

2.18 Strings Are Immutable

69

https://E-next.in
It is tempting to use the [] operator 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"
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
greeting[0] = "J"
TypeError: 'str' object does not support item assignment
>>> print(greeting)
Hello, world!

Instead of producing the output Jello, world!, this code produces the runtime error
TypeError:’str’ object doesn’t support item assignment. Strings are immutable, which
means you can’t change an existing string. The best you can do is create a new string
that is a variation on the original:

>>> greeting = "Hello, world!"


>>> newGreeting = "J" + greeting[1:]
>>> print(newGreeting)
Jello, world!
The solution here is to concatenate a new first letter onto a slice of greeting. This
operation has no effect on the original string.

2.19 Searching

It determines if string str occurs in string, or in a substring of string if starting


index beg and ending index end are given.

Syntax
str.find(str, beg=0, end=len(string))

Parameters
 str -- This specifies the string to be searched.
 beg -- This is the starting index, by default its 0.
 end -- This is the ending index, by default its equal to the length of the string.

Return Value
Index if found and -1 otherwise.

Example

>>> str1 = "this is string example....wow!!!"


>>> str2 = "exam"
>>> print(str1.find(str2))
15
>>> print(str1.find(str2, 10))

15

70

https://E-next.in
>>> print(str1.find(str2, 40))
-1

2.20 Looping and Counting

The following program counts the number of times the letter a appears in a string and
is an example of a counter pattern :

>>> fruit = "banana";


>>> count = 0
>>> for char in fruit :
if char == "a" :
count+=1
>>> print(count)
3

2.21 String Methods

In addition to the functions that we have seen so far there is also a special type of
function called a method. You can think of a method as a function which is attached to
a certain type of variable (e.g. a string). When calling a function you just need the
name of the function followed by parentheses (possibly with some arguments inside).
In contrast a method also needs to be associated with a variable (also called an
object). The syntax that is used is the variable (or object) name or a value followed by
a dot followed by the name of the method along with possibly some arguments in
parentheses like this:

VARIABLE.METHODNAME(ARGUMENTS)

You can see that it looks just like a function call except for the variable name and the
dot at the start. Compare how the len function and the upper method are used below.

>>> my_str = "hello world"


>>> len(my_str)
11
>>> my_str.upper()
'HELLO WORLD'

The len function returns the length of the sequence which is given as an argument. The
upper method returns a new string which is the same as the string that it is called upon
except that each character has been converted to uppercase. In each case the original
string remains unchanged.

An example of a method which needs an argument to operate on is the count method.

>>> my_str = "the quick brown fox jumps over the lazy dog."
>>> my_str.count("the")
2
>>> my_str.count("hello")
0

71

https://E-next.in
>>> my_str.count("e")
3

The count method returns the number of times the string given as an argument occurs
within the string that it is called upon. But what about the following:

>>> ms = "ahaha"
>>> ms.count("aha")
1

The str type contains useful methods that manipulate strings. To see what methods are
available, use the dir function with str as an argument.
>>> dir(str)

which will return the list of items associated with strings:


[' add ', ' class ', '__contains ', ' delattr__', ' dir ', ' doc ', '__eq ',
' format ', ' ge ', '__getattribute ', ' getitem ', ' getnewargs ', ' gt ',
' hash ', ' init ', ' init_subclass ', ' iter__', ' le ', ' len ', ' lt ',
' mod ', ' mul ', '__ne ', ' new ', ' reduce ', ' reduce_ex ', ' repr ',
' rmod ', ' rmul ', ' setattr ', ' sizeof ', ' str ', ' subclasshook ',
'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find',
'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier',
'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower',
'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper',
'zfill']

To find out more about an item in this list, we can use the help command:

>>> help(str.capitalize)
Help on method_descriptor:

capitalize(...)
S.capitalize() -> str

Return a capitalized version of S, i.e. make the first character


have upper case and the rest lower case.

We can call any of these methods using dot notation:

>>> s = "brendan"
>>> s.capitalize()
'Brendan'

Calling the help function prints out the docstring:

>>> help(str.find)
Help on method_descriptor:

find(...)

72

https://E-next.in
S.find(sub[, start[, end]]) -> int

Return the lowest index in S where substring sub is found,


such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.

Return -1 on failure.

The parameters in square brackets are optional parameters. We can use str.find to find
the location of a character in a string:

>>> fruit = "banana"


>>> index = fruit.find('a')
>>> print(index)
1
Or a substring:

>>> fruit.find("na")
2

It also takes an additional argument that specifies the index at which it should start:

>>> fruit.find("na",3)
4

And has a second optional parameter specifying the index at which the search should
end:

>>> "bob".find("b",1,2)
-1

In this example, the search fails because the letter b does not appear in the index range
from 1 to 2 (not including 2).

2.22 The in operator

The in operator tests if one string is a substring of another:

>>> "p" in "apple"


True
>>> "i" in "apple"
False
>>> "ap" in "apple"
True
>>> "pa" in "apple"
False

Note that a string is a substring of itself:

>>> "a" in "a"

73

https://E-next.in
True
>>> "apple" in "apple"
True

Combining the in operator with string concatenation using +, we can write a function
that removes all the vowels from a string:

def remove_vowels(s):
# vowels contains all the letters we want to remove
vowels = "aeiouAEIOU"
s_without_vowels = ""
# scan through each letter in the input string
for letter in s:
# check if the letter is not in the disallowed list of letters
if letter not in vowels:
# the letter is allowed, add it to the result
s_without_vowels += letter
return s_without_vowels

Test this function to confirm that it does what we wanted it to do.

2.23 String Comparison

The comparison operators work on strings. To see if two strings are equal:

>>> if word < "banana":


print("Your word," + word + ", comes before banana.")
elif word > "banana":
print("Your word," + word + ", comes after banana.")
else:
print("Yes, we have no bananas!")

You should be aware, though, that Python does not handle upper- and lowercase letters
the same way that people do. All the uppercase letters come before all the lowercase
letters. As a result:

Your word,zebra, comes after banana.

A common way to address this problem is to convert strings to a standard format, such
as all lowercase, before performing the comparison. A more difficult problem is
making the program realize that zebras are not fruit.

2.24 String Operations

S. No. Methods with Description

capitalize()
1
Capitalizes first letter of string

74

https://E-next.in
center(width, fillchar)

2
Returns a string padded with fillchar with the original string centered to
a total of width columns.

count(str, beg= 0,end=len(string))

3
Counts how many times str occurs in string or in a substring of string if
starting index beg and ending index end are given.

decode(encoding='UTF-8',errors='strict')

4
Decodes the string using the codec registered for encoding. encoding
defaults to the default string encoding.

encode(encoding='UTF-8',errors='strict')

5
Returns encoded string version of string; on error, default is to raise a
ValueError unless errors is given with 'ignore' or 'replace'.

6 endswith(suffix, beg=0, end=len(string))


Determines if string or a substring of string (if starting index beg and
ending index end are given) ends with suffix; returns true if so and
false otherwise.
expandtabs(tabsize=8)

7
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if
tabsize not provided.

find(str, beg=0 end=len(string))

8
Determine if str occurs in string or in a substring of string if starting
index beg and ending index end are given returns index if found and -1
otherwise.
index(str, beg=0, end=len(string))
9
Same as find(), but raises an exception if str not found.

isalnum()

10
Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.

75

https://E-next.in
isalpha()

11
Returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.

isdigit()
12
Returns true if the string contains only digits and false otherwise.

islower()

13
Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false otherwise.

isnumeric()

14
Returns true if a unicode string contains only numeric characters and
false otherwise.

isspace()
15
Returns true if string contains only whitespace characters and false
otherwise.
istitle()
16
Returns true if string is properly "titlecased" and false otherwise.

isupper()

17
Returns true if string has at least one cased character and all cased
characters are in uppercase and false otherwise.

join(seq)

18
Merges (concatenates) the string representations of elements in
sequence seq into a string, with separator string.

len(string)
19
Returns the length of the string

76

https://E-next.in
ljust(width[, fillchar])

20
Returns a space-padded string with the original string left-justified to
a total of width columns.

lower()
21
Converts all uppercase letters in string to lowercase.

lstrip()
22
Removes all leading whitespace in string.

maketrans()
23
Returns a translation table to be used in translate function.

max(str)
24
Returns the max alphabetical character from the string str.

min(str)
25
Returns the min alphabetical character from the string str.

replace(old, new [, max])

26
Replaces all occurrences of old in string with new or at most max
occurrences if max given.

rfind(str, beg=0,end=len(string))
27
Same as find(), but search backwards in string.

rindex( str, beg=0, end=len(string))


28
Same as index(), but search backwards in string.

77

https://E-next.in
rjust(width,[, fillchar])

29
Returns a space-padded string with the original string right-justified to
a total of width columns.

rstrip()
30
Removes all trailing whitespace of string.

split(str="", num=string.count(str))

31
Splits string according to delimiter str (space if not provided) and
returns list of substrings; split into at most num substrings if given.

splitlines( num=string.count('\n'))

32
Splits string at all (or num) NEWLINEs and returns a list of each line
with NEWLINEs removed.

startswith(str, beg=0,end=len(string))

33 Determines if string or a substring of string (if starting index beg and


ending index end are given) starts with substring str; returns true if
so and false otherwise.

strip([chars])
34
Performs both lstrip() and rstrip() on string

swapcase()
35
Inverts case for all letters in string.

title()

36
Returns "titlecased" version of string, that is, all words begin with
uppercase and the rest are lowercase.

translate(table, deletechars="")

37
Translates string according to translation table str(256 chars), removing
those in the del string.

78

https://E-next.in
upper()
38
Converts lowercase letters in string to uppercase.

zfill (width)

39
Returns original string leftpadded with zeros to a total of width
characters; intended for numbers, zfill() retains any sign given (less
one zero).
isdecimal()

40
Returns true if a unicode string contains only decimal characters and
false otherwise.

79

https://E-next.in

You might also like