Unit Ii

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 30

UNIT II

DATA, EXPRESSIONS, STATEMENTS


2.1 THE PYTHON INTERPRETER
The Python programming language was conceived in the late 1980s, and its
implementation was started in December 1989 by Guido van Rossum at CWI in the
Netherlands as a successor to the ABC programming language. When he began implementing
Python, Guido van Rossum was also reading the published scripts from “Monty Python’s
Flying Circus‖, a BBC comedy series from the 1970s. Van Rossum thought he needed a
name that was short, unique, and slightly mysterious, so he decided to call the language
Python.

Python is a cross-platform programming language, meaning, it runs on


multiple platforms like Windows, Mac OS X, Linux, Unix and has even been ported to the
Java and .NET virtual machines. It is free and open source.

2.1.1 Starting the Interpreter


The Python interpreter is a program that reads and executes Python
code.Even though most of today‘s Linux and Mac have Python preinstalled in it, the version
might be out-of-date. So, it is always a good idea to install the most current version.

After installation, the python interpreter lives in the installed directory.

By default it is /usr/local/bin/pythonX.X in Linux/Unix and C:\PythonXX in


Windows, where the 'X' denotes the version number. To invoke it from the shell or the
command prompt we need to add this location in the search path.

Search path is a list of directories (locations) where the operating system


searches for executables. For example, in Windows command prompt, we can type set path=
%path%;c:\python27 (python27 means version 2.7, it might be different in your case) to add
the location to path for that particular session.In Mac OS we need not worry about this as the
installer takes care about the search path.

Now there are two ways to start Python.

Python Mode

Script Mode Interactive Mode

Figure 2.1 Modes of Python Interpreter


2.1.2 Interactive Mode
Typing python in the command line will invoke the interpreter in interactive mode.
When it starts, you should see output like this:

PYTHON 2.7.13 (V2.7.13:A06454B1AFA1, DEC 17 2016, 20:42:59) [MSC V.1500 32 BIT


(INTEL)] ON WIN32
TYPE "COPYRIGHT", "CREDITS" OR "LICENSE()" FOR MORE INFORMATION.
>>>
The first three lines contain information about the interpreter and the operating system
it‘s running on, so it might be different for you. But you should check that the version
number, which is 2.7.13 in this example, begins with 2, which indicates that you are running
Python 2. If it begins with 3, you are running Python 3.

The last line is a prompt that indicates that the interpreter is ready for you to enter code.
If you type a line of code and hit Enter, the interpreter displays the result:

>>> 5 + 4
9
This prompt can be used as a calculator. To exit this mode type exit() or quit() and press
enter.

2.1.3 Script Mode


This mode is used to execute Python program written in a file. Such a file is called
a script. Scripts can be saved to disk for future use. Python scripts have the extension .py,
meaning that the filename ends with .py.

For example: helloWorld.py


To execute this file in script mode we simply write python helloWorld.py at the
command prompt.

2.1.4 Integrated Development Environment (IDE)

We can use any text editing software to write a Python script file.

We just need to save it with the .py extension. But using an IDE can make our life a lot
easier. IDE is a piece of software that provides useful features like code hinting, syntax
highlighting and checking, file explorers etc. to the programmer for application development.

Using an IDE can get rid of redundant tasks and significantly decrease the time required for
application development.

IDEL is a graphical user interface (GUI) that can be installed along with the Python
programming language and is available from the official website.

We can also use other commercial or free IDE according to our preference.PyScripter IDEis
one of the Open source IDE.

2.1.5 Hello World Example


Now that we have Python up and running, we can continue on to write our first Python
program.

Type the following code in any text editor or an IDE and save it as helloWorld.py

print("Hello world!")

Now at the command window, go to the loaction of this file. You can use the cd command to
change directory.

To run the script, type, python helloWorld.py in the command window. We should be able to
see the output as follows:

Hello world!

If you are using PyScripter, there is a green arrow button on top. Press that button or
press Ctrl+F9 on your keyboard to run the program.

In this program we have used the built-in function print(), to print out a string to the
screen. String is the value inside the quotation marks, i.e. Hello world!.

2.2 VALUES AND TYPES


A value is one of the basic things a program works with, like a letter or a number.
Some example values are 5, 83.0, and 'Hello, World!'.These values belong to different types:
5 is an integer, 83.0 is a floating-point number, and'Hello, World!' is a string, so-called
because the letters it contains are strung together.If you are not sure what type a value has,
the interpreter can tell you:
>>>type(5)
<class 'int'>
>>>type(83.0)
<class 'float'>
>>>type('Hello, World!')
<class 'str'>

In these results, the word ―class‖ is used in the sense of a category; a type is
a category ofvalues.Not surprisingly, integers belong to the type int, strings belong to str and
floating-pointnumbers belong to float.What about values like '5' and '83.0'? They look like
numbers, but they are in quotationmarks like strings.
>>>type('5')
<class 'str'>
>>>type('83.0')
<class 'str'>

They‘re strings.When you type a large integer, you might be tempted to use commas
between groups ofdigits, as in 1,000,000. This is not a legal integer in Python, but it is legal:
>>> 1,000,000
(1, 0, 0)
That‘s not what we expected at all! Python interprets 1,000,000 as a comma-
separatedsequence of integers. We‘ll learn more about this kind of sequence later.
2.2.1 Standard Data Types
Python has various standard data types that are used to define the operationspossible
on them and the storage method for each of them.
Python has five standard data types −
 Numbers
 String
 List
 Tuple
 Dictionary
2.2.1.1 Python Numbers
Number data types store numeric values. Number objects are created when you assign
a value to them. For example –
var1 =1
var2 =10
You can also delete the reference to a number object by using the del statement. The
syntax of the del statement is −
del var1[,var2[,var3[...,varN]]]]
You can delete a single object or multiple objects by using the del statement. For
example −
delvar
delvar_a,var_b
Python supports four different numerical types −
 int (signed integers)
 long (long integers, they can also be represented in octal and hexadecimal)
 float (floating point real values)
 complex (complex numbers)
Examples
Here are some examples of numbers –

Table 2.1: Different number format example

int long float complex

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-786 0122L -21.9 9.322e-36j

080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j

-0490 535633629843L -90. -.6545+0J

-0x260 -052318172735L -32.54e100 3e+26J


0x69 -4721885298529L 70.2-E12 4.53e-7j

 Python allows you to use a lowercase l with long, but it is recommended that you use
only an uppercase L to avoid confusion with the number 1. Python displays long
integers with an uppercase L.
 A complex number consists of an ordered pair of real floating-point numbers denoted
by x + yj, where x and y are the real numbers and j is the imaginary unit.
2.2.1.2 Python Strings
Strings in Python are identified as a contiguous set of characters represented
in the quotation marks. Python allows for either pairs 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 at the end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator. For example –

str = 'Python Programming'


printstr # Prints complete string
printstr[0] # Prints first character of the string
printstr[-1] # Prints last character of the string
printstr[2:5] # Prints characters starting from 3rd to 5th
printstr[2:] # Prints string starting from 3rd character
printstr * 2 # Prints string two times
printstr + " Course" # Prints concatenated string
This will produce the following result –

Python Programming
P
g
tho
thon Programming
Python ProgrammingPython Programming
Python Programming Course
2.2.1.3 Python Lists
Lists are the most versatile of Python's compound data types. A list contains
items separated by commas and enclosed within square brackets ([]). To some extent, lists
are similar to arrays in C. One difference between them is that all the items belonging to a
list can be of different data type.

The values stored in a list can be accessed using the slice operator ([ ] and [:])
with indexes starting at 0 in the beginning of the list and working their way to end -1. The
plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.
For example −

list = [ 'Hai', 123 , 1.75, 'vinu', 100.25 ]


smalllist = [251, 'vinu']
print list # Prints complete list
print list[0] # Prints first element of the list
print list[-1] # Prints last element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
printsmalllist * 2 # Prints list two times
print list + smalllist # Prints concatenated lists
This produces the following result –

['Hai', 123, 1.75, 'vinu', 100.25]


Hai
100.25
[123, 1.75]
[1.75, 'vinu', 100.25]
[251, 'vinu', 251, 'vinu']
['Hai', 123, 1.75, 'vinu', 100.25, 251, 'vinu']
2.2.1.4 Python Boolean
A Boolean type was added to Python 2.3. Two new constants were added
tothe builtin module, True and False. True and False are simply set to integer values of
1 and 0 and aren't a different type.
The type object for this new type is named bool; the constructor for it takes any Python value
and converts it to True or False.

>>>bool(1)
True
>>>bool(0)
False
Python's Booleans were added with the primary goal of making code clearer.
For example, if you're reading a function and encounter the statement return 1, you might
wonder whether the 1 represents a Boolean truth value, an index, or a coefficient that
multiplies some other quantity. If the statement is return True, however, the meaning of the
return value is quite clear.
Python's Booleans were not added for the sake of strict type-checking. A very
strict language such as Pascal would also prevent you performing arithmetic with Booleans,
and would require that the expression in an if statement always evaluate to a Boolean result.
Python is not this strict and never will be. This means you can still use any expression in
an if statement, even ones that evaluate to a list or tuple or some random object. The Boolean
type is a subclass of the int class so that arithmetic using a Boolean still works.
>>> True + 1
2
>>> False + 1
1
>>> False * 85
0
>>> True * 85
85
>>>True+True
2
>>>False+False
0

We will discuss about data types like Tuple, Dictionary in Unit IV.

2.2.2 Data Type Conversion

Sometimes, you may need to perform conversions between the built-in types.
To convert between types, you simply use the type name as a function.

There are several built-in functions to perform conversion from one data type
to another. These functions return a new object representing the converted value.

Table 2.2: Data Type Conversion

Function Description

int(x [,base]) Converts x to an integer. base specifies the base if x is a string.

long(x [,base] ) Converts x to a long integer. base specifies the base if x is a


string.

float(x) Converts x to a floating-point number.

complex(rea Creates a complex number.


l [,imag])

str(x) Converts object x to a string representation.

repr(x) Converts object x to an expression string.

eval(str) Evaluates a string and returns an object.

list(s) Converts s to a list.

chr(x) Converts an integer to a character.

unichr(x) Converts an integer to a Unicode character.

ord(x) Converts a single character to its integer value.


hex(x) Converts an integer to a hexadecimal string.

oct(x) Converts an integer to an octal string.

2.3 VARIABLES

A variable is a name that refers to a value. Variable reserved memory


locations to store values. This means that when you create a variable you reserve some space
in memory. Based on the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory.

2.3.1 Assignment Statements

An assignment statement creates a new variable and gives it a value:

>>>message = 'Introducing Python Variable'


>>>num = 15
>>>radius = 5.4
This example makes three assignments. The first assigns a string to a new
variable named message; the second gives the integer 15 to num; the third assigns floating
point value 5.4 to variable radius.

2.3.2 Variable Names

Programmers generally choose names for their variables that are meaningful

The Rules

 Variables names must start with a letter or an underscore, such as:


o _mark
o mark_
 The remainder of your variable name may consist of letters, numbers and underscores.
o subject1
o my2ndsubject
o un_der_scores
 Names are case sensitive.
o case_sensitive, CASE_SENSITIVE, and Case_Sensitive are each a different
variable.
 Can be any (reasonable) length
 There are some reserved (KeyWords)words which you cannot use as a variable name
because Python uses them for other things.

The interpreter uses keywords to recognize the structure of the program, and
they cannot be used as variable names.
Python 3 has these keywords:

False class finally is return None

continue for lambda try True def

from nonlocal while and del global

not with as elif if or

yield assert else import pass break

except in raise

You don‘t have to memorize this list. In most development environments,


keywords are displayed in a different color; if you try to use one as a variable name, you‘ll
know.

If you give a variable an illegal name, you get a syntax error:

>>>1book = 'python'
SyntaxError: invalid syntax
>>>more@ = 1000000
SyntaxError: invalid syntax
>>>class = 'Fundamentals of programming'
SyntaxError: invalid syntax
1book is illegal because it begins with a number. more@ is illegal because it
contains an illegal character, @. class is illegal because it is a keyword.
Good Variable Name

 Choose meaningful name instead of short name. roll_no is better than rn.
 Maintain the length of a variable name. Roll_no_of_a_student is too long?
 Be consistent; roll_no or orRollNo
 Begin a variable name with an underscore(_) character for a special case.
2.4 EXPRESSIONS AND STATEMENTS
An expression is a combination of values, variables, and operators. A value
all by itself is considered an expression, and so is a variable, so the following are all legal
expressions:
>>> 50
50
>>> 10<5
False
>>> 50+20
70
When you type an expression at the prompt, the interpreter evaluates it, which
means that it finds the value of the expression.
A statement is a unit of code that has an effect, like creating a variable or
displaying a value.

>>> n = 25

>>>print(n)

The first line is an assignment statement that gives a value to n. The second
line is a print statement that displays the value of n. When you type a statement, the
interpreter executes it, which means that it does whatever the statement says. In general,
statements don‘t have values.

2.4.1 Difference Between a Statement and an Expression


A statement is a complete line of code that performs some action, while an
expression is any section of the code that evaluates to a value. Expressions can be combined
―horizontally‖ into larger expressions using operators, while statements can only
be combined ―vertically‖ by writing one after another, or with block constructs.
Every expression can be used as a statement, but most statements cannot be used as
expressions.
2.5 OPERATORS
In this section, you'll learn everything about different types of operators in
Python, their syntax and how to use them with examples.

Operators are special symbols in Python that carry out computation. The value
that the operator operates on is called the operand.

For example:

>>>10+5
15

Here, + is the operator that performs addition. 10 and 5 are the operands and 15 is the output
of the operation. Python has a number of operators which are classified below.

 Arithmetic operators
 Comparison (Relational) operators
 Logical (Boolean) operators
 Bitwise operators
 Assignment operators
 Special operators

2.5.1 Arithmetic Operators


Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication etc.
Table 2.3: Arithmetic operators in Python

Operator Meaning Example


+ Add two operands or unary plus x + y
+2
- Subtract right operand from the left or unary minus x - y
-2
* Multiply two operands x*y
/ Divide left operand by the right one (always results into x / y
float)
% Modulus - remainder of the division of left operand by the x % y (remainder
right of x/y)
// Floor division - division that results into whole number x // y
adjusted to the left in the number line
** Exponent - left operand raised to the power of right x**y (x to the
power y)

Example
x=7
y=3
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x % y =',x%y)
print('x ** y =',x**y)
When you run the program, the output will be:
x + y = 10
x-y=4
x * y = 21
x / y = 2.3333333333333335
x // y = 2
x%y=1
x ** y = 343
2.5.2 Comparison or Relational Operators

Comparison operators are used to compare values. It either


returns True or False according to the condition.

Table 2.4:Comparison Operators in Python

Operator Meaning Example


> Greater that - True if left operand is greater than the right x>y
< Less that - True if left operand is less than the right x<y
== Equal to - True if both operands are equal x == y
!= Not equal to - True if operands are not equal x != y
>= Greater than or equal to - True if left operand is greater than or equal x >= y
to the right
<= Less than or equal to - True if left operand is less than or equal to the x <= y
right

Example
x=5
y=7
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)
When you run the program, the output will be:
x >y is False
x <y is True
x == y is False
x != y is True
x >= y is False
x <= y is True
2.5.3 Logical Operators

Logical operators are the and, or, not operators.

Table 2.5: Logical operators in Python

Operator Meaning Example


and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x

Example
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
When you run the program, the output will be:
x and y is False
x or y is True
not x is False
2.5.4 Bitwise Operators
Bitwise operators act on operands as if they were string of binary digits. It
operates bit by bit, hence the name.

For example, 2 is 10 in binary and 7 is 111.

In Table 2.6: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Table 2.6: Bitwise operators in Python

Operator Meaning Example


& Bitwise AND x& y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x>> 2 = 2 (0000 0010)
<< Bitwise left shift x<< 2 = 40 (0010 1000)

Example
x=10
y=4
print('x& y=',x& y)
print('x | y=',x | y)
print('~x=',~x)
print('x ^ y=',x ^ y)
print('x>> 2=',x>> 2)
print('x<< 2=',x<< 2)
When you run the program, the output will be:
x& y= 0
x | y= 14
~x= -11
x ^ y= 14
x>> 2= 2
x<< 2= 40
2.5.5 Assignment Operators

Assignment operators are used in Python to assign values to variables.

a = 10 is a simple assignment operator that assigns the value 10 on the right to


the variable a on the left.

There are various compound operators in Python like a += 10 that adds to the
variable and later assigns the same. It is equivalent to a = a + 10.
Table 2.7: Assignment operators in Python

Operator Example Equivatent to


= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5
2.5.6 Special Operators
Python language offers some special type of operators like the identity
operator or the membership operator. They are described below with examples.

2.5.6.1 Identity Operators

is and is not are the identity operators in Python. They are used to check if two values (or
variables) are located on the same part of the memory. Two variables that are equal does not
imply that they are identical.

Table 2.8: Identity operators in Python

Operator Meaning Example


is True if the operands are identical (refer to the same object) x is True
is not True if the operands are not identical (do not refer to the same x is not
object) True

Example
x1 = 7
y1 = 7
x2 = 'Welcome'
y2 = 'Welcome'
x3 = [1,2,3]
y3 = [1,2,3]
print(x1 is not y1)
print(x2 is y2)
print(x3 is y3)
When you run the program, the output will be:
False
True
False

Here, we see that x1 and y1 are integers of same values, so they are equal as
well as identical. Same is the case with x2 and y2 (strings).But x3 and y3 are list. They are
equal but not identical. Since list are mutable (can be changed), interpreter locates them
separately in memory although they are equal.

2.5.6.2 Membership Operators


in and not in are the membership operators in Python. They are used to test whether a value
or variable is found in a sequence (string, list, tuple, set and dictionary).

Table 2.9: Membership operators in Python

Operator Meaning Example


in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x

Example
x = 'Python Programming'
print('Program' not in x)
print('Program' in x)
print('program' in x)
When you run the program, the output will be:
False
True
False
Here, ' Program ' is in x but ' program' is not present in x, since Python is case
sensitive.
2.6 PRECEDENCE OF PYTHON OPERATORS
The combination of values, variables, operators and function calls is termed as
an expression. Python interpreter can evaluate a valid expression. When an expression
contains more than one operator, the order of evaluation dependson the Precedence of
operations.

For example, multiplication has higher precedence than subtraction.

>>> 20 – 5*3
5
But we can change this order using parentheses () as it has higher precedence.
>>> (20 - 5) *3
45
The operator precedence in Python are listed in the following table. It is in
descending order, upper group has higher precedence than the lower ones.

Table 2.10: Operator precedence rule in Python

Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisions, Identity, Membership operators
not Logical NOT
and Logical AND
or Logical OR

2.7 ASSOCIATIVITY OF PYTHON OPERATORS

We can see in the above table that more than one operator exists in the same
group. These operators have the same precedence.

When two operators have the same precedence, associativity helps to


determine which the order of operations.

Associativity is the order in which an expression is evaluated that has multiple


operator of the same precedence. Almost all the operators have left-to-right associativity.

For example, multiplication and floor division have the same precedence.
Hence, if both of them are present in an expression, left one is evaluates first.

>>> 10 * 7 // 3
23
>>> 10 * (7//3)
20
>>> (10 * 7)//3
23
We can see that 10 * 7 // 3is equivalent to (10 * 7)//3.

Exponent operator ** has right-to-left associativity in Python.

>>> 5 ** 2 ** 3
390625
>>> (5** 2) **3
15625
>>> 5 **(2 **3)
390625
We can see that 2 ** 3 ** 2 is equivalent to 2 ** (3 ** 2).
2.7.1 Non Associative Operators

Some operators like assignment operators and comparison operators do not


have associativity in Python. There are separate rules for sequences of this kind of operator
and cannot be expressed as associativity.

For example, x < y < z neither means (x < y) < z nor x < (y < z). x < y < z is equivalent to x
< y and y < z, and is evaluates from left-to-right.

Furthermore, while chaining of assignments like x = y = z is perfectly valid, x = y += zwill


result into error.

2.8 TUPLE ASSIGNMENT


It is often useful to swap the values of two variables. With conventional
assignments, you have to use a temporary variable. For example, to swap a and b:
>>>temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>>a, b = b, a
The left side is a tuple of variables; the right side is a tuple of expressions.
Each value is assigned to its respective variable. All the expressions on the right side are
evaluated before any of the assignments. The number of variables on the left and the number
of values on the right have to be the
same:
>>>a, b = 1, 2, 3
ValueError: too many values to unpack
More generally, the right side can be any kind of sequence (string, list or
tuple). For example, to split an email address into a user name and a domain, you could write:
>>>addr = 'monty@python.org'
>>>uname, domain = addr.split('@')
The return value from split is a list with two elements; the first element is
assigned to uname, the second to domain.
>>>uname
'monty'
>>>domain
'python.org'

2.9 COMMENTS
As programs get bigger and more complicated, they get more difficult to read.
Formal languages are dense, and it is often difficult to look at a piece of code and figure out
what it is doing, or why. For this reason, it is a good idea to add notes to your programs to
explain in natural language what the program is doing. These notes are called comments, and
they start with the # symbol:
# computeArea of a triangle using Base and Height
area= (base*height)/2
In this case, the comment appears on a line by itself. You can also put
comments at the endof a line:
area= (base*height)/2 # Area of a triangle using Base and Height
Everything from the # to the end of the line is ignored—it has no effect on the
execution ofthe program.Comments are most useful when they document non-obvious
features of the code. It isreasonable to assume that the reader can figure out what the code
does; it is more useful toexplain why.
This comment is redundant with the code and useless:
base= 5 # assign 5 to base
This comment contains useful information that is not in the code:
base = 5 # base is in centimetre.
Good variable names can reduce the need for comments, but long names can
make complexexpressions hard to read, so there is a tradeoff.

If we have comments that extend multiple lines, one way of doing it is to use
hash (#) in the beginning of each line. For example:

#This is a long comment


#and it extends
#to multiple lines

Another way of doing this is to use triple quotes, either ''' or """.

These triple quotes are generally used for multi-line strings. But they can be used as multi-
line comment as well. Unless they are not docstrings, they do not generate any extra code.

"""This is also a
perfect example of
multi-line comments"""
2.9.1 Docstring in Python

Docstring is short for documentation string. It is a string that occurs as the


first statement in a module, function, class, or method definition. We must write what a
function/class does in the docstring. Triple quotes are used while writing docstrings. For
example:

def area(r):
"""Compute the area of Circle"""
return 3.14159*r**2
Docstring is available to us as the attribute doc of the function. Issue the
following code in shell once you run the above program.
>>>print(area. doc )
Compute the area of Circle
2.10. MODULES AND FUNCTIONS

2.10.1 Functions
In the context of programming, a function is a named sequence of statements
that performs a computation. When you define a function, you specify the name and the
sequence of statements. Later, you can ―call‖ the function by name. Functions help break our
program into smaller and modular chunks. As our program grows larger and larger, functions
make it more organized and manageable. Furthermore, it avoids repetition and makes code
reusable.
Functions

Built-in Functions User Define Function

Figure 2.2Types of Functions

Functions can be classified into


 Built-in Functions
 User Defined Functions
2.10.1.1 Built-in Functions
The Python interpreter has a number of functions that are always available for
use. These functions are called built-in functions.We have already seen one example of a
function call:type()
>>>type(25)
<class 'int'>
The name of the function is type. The expression in parentheses is called the
argument of the function. The result, for this function, is the type of the argument.It is
common to say that a function ―takes‖ an argument and ―returns‖ a result. The resultis also
called the return value.
Python provides functions that convert values from one type to another. The
intfunctiontakes any value and converts it to an integer, if it can, or complains otherwise:
>>>int('25')
25
>>>int('Python')
ValueError: invalid literal for int(): Python
intcan convert floating-point values to integers, but it doesn‘t round off; it
chops off thefraction part:
>>>int(9.999999)
9
>>>int(-2.3)
-2
floatconverts integers and strings to floating-point numbers:
>>>float(25)
25.0
>>>float('3.14159')
3.14159
Finally, strconverts its argument to a string:
>>>str(25)
'25'
>>>str(3.14159)
'3.14159'

2.10.1.1.1. range() – function


The range() constructor returns an immutable sequence object of integers
between the given start integer to the stop integer.

Python's range() Parameters


The range() function has two sets of parameters, as follows:
range(stop)

 stop: Number of integers (whole numbers) to generate, starting from zero.


eg. range(3) == [0, 1, 2].

range([start], stop[, step])

 start: Starting number of the sequence.


 stop: Generate numbers up to, but not including this number.
 step: Difference between each number in the sequence.

Note that:

 All parameters must be integers.


 All parameters can be positive or negative.

>>>range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>range(5,10)
[5, 6, 7, 8, 9]
>>>range(10,1,-2)
[10, 8, 6, 4, 2]

2.10.1.1.2. Printing to the Screen


In python 3, print function will prints as strings everything in a comma-
separated sequence of expressions, and it will separate the results with single blanks by
default. Note that you can mix types: anything that is not already a string is automatically
converted to its string representation.
Eg.

>>> x=10
>>> y=7
>>>print('The sum of', x, 'plus', y, 'is', x+y)
The sum of 10 plus 7 is 17
You can also use it with no parameters:

print()

to just advance to the next line.

In python 2, simplest way to produce output is using the print statementwhere


you can pass zero or more expressions separated by commas. Thisfunction converts the
expressions you pass into a string and writes the result to standard output as follows

>>> x=10
>>> y=7
>>>print'The sum of', x, 'plus', y, 'is', x+y
The sum of 10 plus 7 is 17

2.10.1.1.3. Reading Keyboard Input

Python provides two built-in functions to read a line of text from standard
input, which by default comes from the keyboard. These functions are −

 raw_input

 input

The raw_input Function


The raw_input([prompt]) function reads one line from standard input and
returns it as a string.

>>>str = raw_input("Enter your input: ");


Enter your input: range(0,10)
>>> print "Received input is : ", str
Received input is : range(0,10)
This prompts you to enter any string and it would display same string on the
screen.

The input Function


The input([prompt]) function is equivalent to raw_input, except that it
assumes the input is a valid Python expression and returns the evaluated result to you.

>>>str = input("Enter your input: ");


Enter your input: range(0,10)
>>> print "Received input is : ", str
Received input is : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Input data is evaluated and the list is generated

2.10.1.2 User-defined functions


As you already know, Python gives you many built-in functions like print(),
input(), type() etc. but you can also create your own functions. These functions are
called user-defined functions.

2.10.1.2.1 Function Definition and Use


Syntax of Function definition
deffunction_name(parameters):
"""docstring"""
statement(s)

Above shown is a function definition which consists of following components.

1. Keyword def marks the start of function header.


2. A function name to uniquely identify it. Function naming follows the same rules of
writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are
optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements must
have same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.

Example of a function
def welcome(person_name):
"""This function welcome
the person passed in as
parameter"""
print(" Welcome " , person_name , " to Python Function Section")

Using Function or Function Call

Once we have defined a function, we can call it from another function,


program or even the Python prompt. To call a function we simply type the function name
with appropriate parameters.
>>>welcome('Vinu')
Welcome Vinu to Python Function Section

The return statement


The return statement is used to exit a function and go back to the place from
where it was called.

Syntax of return
return [expression_list]

This statement can contain expression which gets evaluated and the value is
returned. If there is no expression in the statement or the return statement itself is not present
inside a function, then the function will return the None object.

defabsolute_value(num):
"""This function returns the absolute
value of the entered number"""

ifnum>= 0:
returnnum
else:
return -num
print(absolute_value(5))
print(absolute_value(-7))

When you run the program, the output will be:


5
7
2.10.2 Flow of Execution
To ensure that a function is defined before its first use, you have to know the order
statements run in, which is called the flow of execution. 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.Figure 2.3 show the flow of execution

Figure 2.3 Flow of execution when function Call


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 run the statements in
another function. Then, while running that new function, the program might have to run yet
another function! Fortunately, Python is good 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.
In summary, when you read a program, you don‘t always want to read from
top to bottom. Sometimes it makes more sense if you follow the flow of execution.
2.10.3 Parameters and Arguments
Some of the functions we have seen require arguments. For example, when
you call type() you pass a variable or value as an argument. Some functions take more than
one argument: eg, range() function take one or two or three arguments.

Inside the function, the arguments are assigned to variables called


parameters. Here is a definition for a function that takes an argument:

def welcome(person_name):
print(" Welcome " , person_name , " to Python Function Section")
This function assigns the argument to a parameter named person_name. When
the function is called, it prints the value of the parameter (whatever it is). This function works
with any value that can be printed.

>>>welcome("Vinu")
Welcome Vinu to Python Function Section
>>>welcome(100)
Welcome 100 to Python Function Section
>>>welcome(50.23)
Welcome 50.23 to Python Function Section
The argument is evaluated before the function is called, so in the below
examples the expressions 'vinu'*3 is evaluated.

>>>welcome('vinu'*3)
Welcome vinuvinuvinu to Python Function Section

You can also use a variable as an argument:

>>>student_name='Ranjith'
>>>welcome(student_name)
Welcome Ranjith to Python Function Section

2.10.4 Modules
A module allows you to logically organize your Python code. Grouping
related code into a module makes the code easier to understand and use. A module is a file
that contains a collection of related functions. Python has lot of built-in modules; math
module is one of them. math module provides most of the familiar mathematical functions.
Before we can use the functions in a module, we have to import it with an
import statement:
>>> import math
This statement creates a module object named math. If you display the
module object, youget some information about it:
>>>math
<module 'math' (built-in)>
The module object contains the functions and variables defined in the module.
To access one of the functions, you have to specify the name of the module and the name of
the function, separated by a dot (also known as a period). This format is called dot notation.
>>>math.log10(200)
2.3010299956639813
>>>math.sqrt(10)
3.1622776601683795
Math module have functions like log(), sqrt(), etc… In order to know what are
the functions available in particular module, we can use dir() function after importing
particular module. Similarly if we want to know detail description about a particular module
or function or variable means we can use help() function.
Eg.
>>> import math
>>>dir(math)
[' doc ', ' name ', ' package ', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh',
'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor',
'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p',
'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
>>>help(pow)
Help on built-in function pow in module builtin :

pow(...)
pow(x, y[, z]) -> number

With two arguments, equivalent to x**y. With three arguments,


equivalent to (x**y) % z, but may be more efficient (e.g. for longs).

2.10.4.1 Writing modules


Any file that contains Python code can be imported as a module. For example,
suppose you have a file named addModule.py with the following code:
def add(a, b):
result = a + b
print(result)
add(10,20)
If you run this program, it will add 10 and 20 and print 30. We can import it
like this:
>>> import addModule
30
Now you have a module object addModule
>>>addModule
<module 'addModule' from 'G:/class/python/code\addModule.py'>
The module object provides add():
>>>addModule.add(120,150)
270
So that‘s how you write modules in Python.
The only problem with this example is that when you import the module it
runs the test code at the bottom. Normally when you import a module, it defines new
functions but it doesn‘t run them.

Programs that will be imported as modules often use the following idiom:
if name == ' main ':
add(10,20)
name is a built-in variable that is set when the program starts. If the
program is running as a script, name has the value ' main '; in that case, the test code
runs. Otherwise, if the module is being imported, the test code is skipped. Modify
addModule.py file as given below.
def add(a, b):
result = a + b
print(result)
if name == ' main ':
add(10,20)
Now while importing addModule test case is not running
>>> import addModule
name has module name as its value when it is imported. Warning: If you
import a module that has already been imported, Python does nothing. It does not re-read the
file, even if it has changed. If you want to reload a module, you can use the built-in function
reload, but it can be tricky, so the safest thing to do is restart the interpreter and then import
the module again.

2.11 ILLUSTRATIVE PROGRAMS

2.11.1 Exchange the Value of two Variables


In python exchange of values of two variables (swapping) can be done in
different ways

 Using Third Variable


 Without Using Third Variable
o Using Tuple Assignment method
o Using Arithmetic operators
o Using Bitwise operators

2.11.1.1 Using Third Variable

1 var1 = input("Enter value of variable1: ")


2 var2 = input("Enter value of variable2: ")
3 temp = var1
4 var1 = var2
5 var2 = temp
6 print("After swapping:")
7 print("First Variable =",var1,)
8 print("Second Variable=",var2,)
When you run the program, the output will be:
Enter value of variable1: 5
Enter value of variable2: 10
After swapping:
First Variable = 10
Second Variable= 5
In the above program line number 3,4,5, are used to swap the values of two variables. In this
program, we use the temp variable to temporarily hold the value of var1. We then put the
value of var2 in var1 and later temp in var2. In this way, the values get exchanged. In this
method we are using one more variable other than var1,var2. So we calling it as swapping
with the use of third variable.
2.11.1.2 Without Using Third Variable

We can do the same swapping operation even without the use of third variable,
There are number of ways to do this, they are.

2.11.1.2.1 Using Tuple Assignment method

In this method inthe above programinstead of line number 3,4,5 use a single
tuple assignment statement
var1 , var2 = var2 , var1
The left side is a tuple of variables; the right side is a tuple of expressions.
Each value is assigned to its respective variable. All the expressions on the right side are
evaluated before any of the assignments.

2.11.1.2.2 Using Arithmetic operators

If the variables are both numbers, Swapping can be performed using simple
mathematical addition subtraction relationship or multiplication division relationship.

Addition and Subtraction

In this method inthe above program instead of line number 3,4,5 use the following
code

x=x+y
y=x-y
x=x-y
Multiplication and Division

In this method inthe above program instead of line number 3,4,5 use the following
code

x=x*y
y=x/y
x=x/y
2.11.1.2.3 Using Bitwise operators

If the variables are integers then we can perform swapping with the help of bitwise
XOR operator. In order to do this in the above program instead of line number 3,4,5 use the
following code
x=x^y
y=x^y
x=x^y

2.11.2 Circulate the Value of N Variables


Problem of circulating a Python list by an arbitrary number of items to the
right or left can be easily performed by List slicing operator.

1 2 3 4 5 6 7
Figure 2.4.aExample List

Consider the above list Figure 2.4.a; circulation of the above list by n position
can be easily achieved by slicing the array into two and concatenating them. Slicing is done
as nth element to end element + beginning element to n-1 th element. Suppose n=2 means,
given list is rotated 2 positions towards left side as given in Figure 2.4.b

3 4 5 6 7 1 2
Figure 2.4.b Left Circulated List

Suppose n= - 2 means, given list is rotated 2 position towards right side as


given in Figure 2.4.c

6 7 1 2 3 4 5
Figure 2.4.c Right Circulated List

So the simple function to perform this circulation operation is

def circulate(list, n):


return list[n:] + list[:n]

>>>circulate([1,2,3,4,5,6,7], 2)
[3, 4, 5, 6, 7, 1, 2]
>>>circulate([1,2,3,4,5,6,7], -2)
[6, 7, 1, 2, 3, 4, 5]

2.11.3 Test for Leap Year


In order to check whether a year is leap year or not python provide a isleap()
function in calendar module. So if you want to check whether a year is leap year or not, first
import calendar module. Then use the isleap() function.

>>> import calendar


>>>calendar
<module 'calendar' from 'C:\Python27\lib\calendar.pyc'>
>>>calendar.isleap(2003)
False
>>> import calendar
>>>calendar.isleap(2000)
True
>>>calendar.isleap(2004)
True
>>>calendar.isleap(2003)
False
>>>calendar.isleap(1900)
False
>>>calendar.isleap(2020)
True

You might also like