0% found this document useful (0 votes)
39 views45 pages

Py Unit - 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views45 pages

Py Unit - 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

2.

1 Introduction to Python
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.
The different versions of python along with the release dates are as follows:
Python 1.0 - January 1994

Python 1.5 - December 31, 1997

Python 1.6 - September 5, 2000

Python 2.0 - October 16, 2000

Python 2.1 - April 17, 2001

Python 2.2 - December 21, 2001

Python 2.3 - July 29, 2003

Python 2.4 - November 30, 2004

Python 2.5 - September 19, 2006

Python 2.6 - October 1, 2008


2. 2 Problem Solving and Python Programming

Python 2.7 - July 3, 2010

Python 3.0 - December 3, 2008

Python 3.1 - June 27, 2009

Python 3.2 - February 20, 2011

Python 3.3 - September 29, 2012

Python 3.4 - March 16, 2014

Python 3.5 - September 13, 2015

Python 3.6 - December 23, 2016

Python 3.7 - June 27, 2018

Python 3.8 – October 14, 2019

Python 3.9 - October 5, 2020

Python 3.10 - October 4, 2021

Python 3.10.4, documentation released on 24 March 2022

2.1.1 Features of Python


Python is a very simple language surrounded by a large library of add-on
functions (modules). It is a platform-independent, scripted and dynamic language,
that allows more run-time flexibility than statically compiled languages.
££ Simple and Easy to learn
££ Free and Open source Software
££ High level Language
££ Portable
££ Interpreted and Interactive
££ Object Oriented
££ Scalable
££ Extendable
££ Embedded
££ GUI Programming and Databases
££ Broad Standard Library
Data, Expressions Statements 2.3

2. 2 Python Setup
To download and Install the Python interpreter (and bundled IDLE program)
go to http://www.python.org/download/. Options available on Python website are as
follows:
Python 3.6
££ Download Windows x86 MSI Installer
££ Download Windows x86-64 MSI Installer
2.2.1 Installation of Python
Linux Environment
Platform to be installed: Centos 7 (RPM based linux).
££ Requirements
££ Memory: 4GB (Recommended)
££ Storage: 100GB
££ Processor: Intel Core i3
££ Kernel: 3.10
Windows Environment
Requirements:
££ 24 Mb of disk space.
2.2.2 Python Keywords
Keywords are reserved words that cannot be used as ordinary identifiers. All
the keywords except True, False and None are in lowercase and they must be written
as it is.
The list of all the keywords are given below
and del from not while as elif global or

with assert else If pass yield break except import

print class exec raise in continue is finally return

def for lambda try True False None

2.2.3 Python Identifiers


Identifiers are names for entities in a program, such as class, variables,
functions etc.
2. 4 Problem Solving and Python Programming

Rules for defining Identifiers


An identifier can be composed of uppercase, lowercase letters, underscore and
digits, but should start only with an alphabet or an underscore.
££ Identifiers can be a combination of lowercase letters (a to z) or uppercase
letters (A to Z) or digits (0 to 9) or an underscore (_).
££ Identifiers cannot start with the digit.
££ Keywords cannot be used as identifiers and identifiers can be any length.
££ No special symbols like !, @, #, $, % etc. are used.
Valid Identifiers sum total averag _ab_ add_1 x1

Invalid Identifiers 1x char x+y

Python is a case-sensitive language. This means, Variable and variable are not
the same
2.2.4 Python Comments
Comments are very important while writing a program. Comment statements
are used to provide a summary of the code in plain English to help future developers
better understand the code.
Single Line comments
1. #This is a comment statement
2. print(‘Hello’)
Multi-line comments
1. #This is a long comment
2. #and it extends
3. 3 #to multiple lines
Another way of using multi-line comments is to use triple quotes, either “ “ “or”
“ “.
1. “ “ “ This is also a
2. perfect example of
3. multi-line comments” “ “
Data, Expressions Statements 2.5

2. 3 The Python Interpreter


Python is considered as an interpreted language because, programs were
executed by an interpreter. The python interpreter can be invoked by typing the
command “python” without any parameter followed by the “return” key at the shell
prompt.
2.3.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 executable. 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.

Figure 2.1 Modes of Python Interpreter


2.3.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:
2. 6 Problem Solving and Python Programming

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

This prompt can be used as a calculator. To exit this mode type exit() or quit()
and press enter.
2.3.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.3.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.
Data, Expressions Statements 2.7

We can also use other commercial or free IDE according to our preference.
PyScripter IDE is one of the Open source IDE.
2.3.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. 4 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)
>>>type(‘5’)
<class’str’>
>>>type(‘83.0’)
2. 8 Problem Solving and Python Programming

In these results, the word class‖ is used in the sense of a category; a


type is a category of values. Not surprisingly, integers belong to the type int, strings
belong to str and floating-point numbers belong to float.What about values like ‘5’
and ‘83.0’? They look like numbers, but they are in quotation marks like strings.
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-


separated sequence of integers. We‘ll learn more about this kind of sequence later.
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
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
Python supports four different numerical types -
Data, Expressions Statements 2.9

delvardelvar_a,var_b

££ 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 –
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

Table 2.1: Different number format example


££ 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.4.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 –
2. 10 Problem Solving and Python Programming

str = ‘Python Programming’ printstr # Prints


complete string
printstr[0]
printstr[-1]printstr[2:5]printstr[2:]printstr
*2

printstr+”Course”
#Prints complete string
#Prints first character of the string
#Prints last character of the string
#Printscharacters startingfrom3rd to 5th
#Prints string startingfrom 3rd character
#Prints stringtwo times
#Printsconcatenatedstring

This will produce the following result –


PythonProgramming
P
g
tho
thonProgramming
PythonProgrammingPythonProgramming
PythonProgrammingCourse

2.4.1.4 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 -
Data, Expressions Statements 2.11

list=[ ‘Hai’,123,1.75,’vinu’,100.25

This produces the following result –\


[‘Hai’,123,1.75, ‘vinu’,100.25]
Hai100.25
[123, 1.75]
[1.75,’vinu’,100.25]
[251,’vinu’,251, ‘vinu’]
[‘Hai’,123,1.75,’vinu’,100.25,251,’vinu’]
>>>bool(1)
True
>>>bool(0)
False

2.4.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.
2. 12 Problem Solving and Python Programming

>>>True+12
>>>False+11
>>>False*85

0
>>>True*8585
>>>True+True2
>>>False+False
0

We will discuss about data types like Tuple, Dictionary in Unit IV.
2.4.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.

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(real Creates a complex number.


[,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.


Data, Expressions Statements 2.13

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

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

Table 2.2: Data Type Conversion


2. 5 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.5.1 Assignment Statements
An assignment statement creates a new variable and gives it a value:
>>>message=’IntroducingPythonVariable’
>>>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.5.2 Variable Names
Programmers generally choose names for their variables that are meaningful
The Rules
1. Variables names must start with a letter or an underscore, such as:
££ _mark
££ mark_
2. The remainder of your variable name may consist of letters, numbers and
underscores.
££ subject1
££ my2ndsubject
££ un_der_scores
4. Names are case sensitive.
££ case_sensitive, CASE_SENSITIVE, and Case_Sensitive are each a
different variable.
££ Can be any (reasonable) length
2. 14 Problem Solving and Python Programming

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:invalidsyntax
>>>more@ = 1000000SyntaxError:invalidsyntax
>>>class= ‘Fundamentalsofprogramming’
SyntaxError:invalidsyntax

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. 6 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:
Data, Expressions Statements 2.15

>>>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.6.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. 7 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.
2. 16 Problem Solving and Python Programming

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.7.1 Arithmetic Operators


Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication etc.
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 x/y


into float)
% Modulus - remainder of the division of left operand by x%y
the right (remainder
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)
Table 2.3: Arithmetic operators in Python
Data, Expressions Statements 2.17

Example

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

Comparison or Relational Operators


Comparison operators are used to compare values. It either returns True or
False according to the condition.
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 x >= y


than or equal to the right
<= Less than or equal to - True if left operand is less than or x <= y
equal to the right
Table 2.4: Comparison Operators in Python
2. 18 Problem Solving and Python Programming

Example
x=5
y=7
print(‘x > yis’,x>y)
print(‘x < yis’,x<y)
print(‘x==yis’,x==y)
print(‘x != y is’,x!=y)
print(‘x>=yis’,x>=y)
print(‘x<=yis’,x

When you run the program, the output will be:


x>yisFalse
x<yisTrue
x==yisFalse
x != y is True
x>=yisFalse
x<=yis True

2.7.3 Logical Operators


Logical operators are the and, or, not operators.
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

Table 2.5 Logical operators in Python


Example

When you run the program, the output will be:


Data, Expressions Statements 2.19

x and y is False
x or y is True
not x is False

2.7.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)
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)


Table 2.6 : Bitwise operators in Python
Example

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. 20 Problem Solving and Python Programming

2.7.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.

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

Table 2.7: Assignment operators in Python


2.7.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.7.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.
Data, Expressions Statements 2.21

Operator Meaning Example

is True if the operands are identical x is True


(refer to the same object)
is not True if the operands are not identical x is not True
(do not refer to the same object)
Table 2.8 : Identity operators in Python
Example

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.7.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).
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 5 not


sequence in x

Table 2.9: Membership operators in Python


2. 22 Problem Solving and Python Programming

Example

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. 8 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 depends on the
Precedence of operators.
For example, multiplication has higher precedence than subtraction.
>>>20–5*35

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.

Operators Meaning

() Parentheses

**` Exponent

+x, -x, ~x Unary plus, Unary minus, Bitwise NOT

*, /, //, % Multiplication, Division, Floor division, Modulus

+, - Addition, Subtraction
Data, Expressions Statements 2.23

<<, >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR
==, !=, >, >=, <, <=,
Comparisions, Identity, Membership operators
is, is not, in, not in
not Logical NOT

and Logical AND

or Logical OR
Table 2.10: Operator precedence rule in Python

2. 9 Associativity 0f 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.

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


Exponent operator ** has right-to-left associativity in Python.
2. 24 Problem Solving and Python Programming

>>> (5** 2) **3


15625
>>> 5 **(2 **3)
390625

We can see that 2 ** 3 ** 2 is equivalent to 2 ** (3 ** 2).


2.9.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. 10 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 cumber some; 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 manyvalues 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:
Data, Expressions Statements 2.25

>>>addr=’[email protected]
>>>uname,domain=addr.split(‘@’)

The return value from split is a list with two elements; the first element is
assigned to
>>>uname’monty’
>>>domain’
python.org’

2. 11 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
Heightarea=(base*height)/2

In this case,the comment appears on a line by itself. You can also put comments
at the end of a line:
area=(base*height)/2#AreaofatriangleusingBase andHeight

Everythingfromthe#totheendofthelineisignored—ithasnoeffectonthe
execution of the program. Comments are most useful when they document non-
obviousfeaturesoft the code. It is reasonable to assume that the reader can figure
out what the code does; it is more useful to explain 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:
2. 26 Problem Solving and Python Programming

Thisisalongcomment#and it extends
#tomultiplelines

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.11.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:
defarea(r):
“””Compute the area of Circle”””return3.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. 12 Modules and Functions


2.12.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.
Data, Expressions Statements 2.27

Figure 2.2 Types of Functions


Functions can be classified into
££ Built-in Functions
££ User Defined Functions
2.12.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 - take - an argument and- returns - a result. The
result is 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

int can convert floating-point values to integers, but it doesn‘t round off; it
chops off the fraction part:
>>>int(9.999999)9
>>>int(-2.3)
-2

Float converts integers and strings to floating-point numbers:


2. 28 Problem Solving and Python Programming

>>>float(25)25.0
>>>float(‘3.14159’)3.14159

Finally, strconverts its argument to a string:


>>>str(25)’25’
>>>str(3.14159)’3.14159’
>>>str(25)‘25’
>>>str(3.14159)‘3.14159’

2.12.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.12.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.
Data, Expressions Statements 2.29

Example .
>>> 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. This function 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

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.
2. 30 Problem Solving and Python Programming

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: “);

Input data is evaluated and the list is generated


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.

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.
Data, Expressions Statements 2.31

Example of a function
def welcome(person_name): “””
This function welcomethe 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 absolutevalue 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. 32 Problem Solving and Python Programming

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.
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:
defwelcome(person_name):
print(“Welcome”,person_name , “to Python Function Section”)
Data, Expressions Statements 2.33

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.12.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:
>>>importmath

This statement creates a module object named math. If you display the
module object, you get some information about it:
>>>math
<module ‘math’ (built-in)>
2. 34 Problem Solving and Python Programming

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.
Example
>>>importmath
>>>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)
Helponbuilt-infunction powinmodulebuiltin:

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

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


equivalentto(x**y) %z,butmaybemoreefficient (e.g.forlongs).

2.12.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:
defadd(a,b):
result=a+b
print(result)
Data, Expressions Statements 2.35

If you run this program, it will add 10 and 20 and print 30. We can import it
like this:
>>>importaddModule
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:
ifname_==
‘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.
defadd(a,b):
result=a+bprint(result)
ifname_==

Now while importing addModule test case is not running


>>>importaddModule

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
2. 36 Problem Solving and Python Programming

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. 13Illustrative Programs
2.13.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
££ Using Tuple Assignment method
££ Using Arithmetic operators
££ Using Bitwise operators

2.13.1.1 Using Third Variable


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.
3.13.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.13.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.
Data, Expressions Statements 2.37

2.13.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 in the 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
2.13.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

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.a Example 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-1th 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
2. 38 Problem Solving and Python Programming

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.13.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
Data, Expressions Statements 2.39

2. 1 With Answers
Two Marks Questions
1. Define python
Python is an object-oriented, high level language, interpreted, dynamic and
multipurpose programming language.
2. Give the features of python.
££ Easy to Use:
££ Expressive Language
££ Interpreted Language
££ Cross-platform language
££ Free and Open Source
££ Object-Oriented language
££ Extensible
3. What is python interpreter?
The engine that translates and runs Python is called the Python Interpreter:
There are two ways to use it: immediate mode and script mode. The >>> is
called the Python prompt. The interpreter uses the prompt to indicate that it
is ready for instructions.
4. What is the difference between intermediate mode and script mode?
££ In immediate mode, you type Python expressions into the Python
Interpreter window, and the interpreter immediately shows the result.
££ Alternatively, you can write a program in a file and use the interpreter to
execute the contents of the file. Such a file is called a script. Scripts have
the advantage that they can be saved to disk, printed, and so on.
5. What is meant by value in python?
A value is one of the fundamental things—like a letter or a number—that a
program manipulates.
6. List the standard data types in python.
Python has five standard data
Types:
££ Numbers ££ List, ££ Dictionary
££ Strings ££ Tuples
2. 40 Problem Solving and Python Programming

7. What is meant by python numbers?


Number data types store numeric values. Number objects are created whenyou
assign a value to them.
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)
8. What are 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 ofstrings 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.
str = ‘Hello World!’
print str[0] # Prints first character of
the string o/p:
H
9. Mention the features of lists in python
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 = [ ‘abcd’, 786 , 2.23,’john’, 70.2 ] print list[0] o/p
££ abcd
Data, Expressions Statements 2.41

10. What is tuple ? What is the difference between list and tuple?
A tuple is another sequence data type that is similar to the list. A tuple consists
of a number of values separated by commas.
The main differences between lists and tuples are: Lists are enclosed in
brackets ( [ ] ) and their elements and size can be changed, while tuples are
enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of
as read-only lists.
Eg: tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )
11. Give the features of python dictionaries
Python’s dictionaries are kind of hash table type. They work like associative
arrays and consist of key-value pairs. A dictionary key can be almost any
Python type, but are usually numbers or strings. Values, on the other hand,
can be any arbitrary Python object.Dictionaries are enclosed by curly braces ({
}) and values can be assigned and accessed using square braces ([]).
For example – dict = {}
dict[‘one’] = “This is one”
12. What is a variable?
One of the most powerful features of a programming language is the ability
to manipulate variables. A variable is a name that refers to a value. The
assignment statement gives a value to a variable.
Eg :
>>> n = 17
>>> pi = 3.14159
13. What are the rules for naming a variable?
Variable names can be arbitrarily long. They can contain both letters and
digits, but they have to begin with a letter or an underscore. Although it is
legal to use uppercase letters, by convention we don‘t. If you do, remember that
case matters.
Bruce and bruce are different variables.
The underscore character ( _) can appear in a name. Eg:
my_name
14. What are keywords?
Keywords are the reserved words in Python. We cannot use a keyword as
2. 42 Problem Solving and Python Programming
2. 14
variable name, function name or any other identifier. They are used to define
the syntax and structure of the Python language In Python, keywords are case
sensitive. There are 33 keywords in Python.
Eg
False, class, finally, return
15. What are the rules for writing an identifier?
££ Identifiers can be a combination of letters in lowercase (a to z) or uppercase
(A to Z) or digits (0 to 9) or an underscore (_). Names like myClass, var_1
and print_this_to_screen, all are valid example.
££ An identifier cannot start with a digit. 1variable is invalid, but variable1
is perfectly fine. Keywords cannot be used as identifiers.
££ We cannot use special symbols like !, @, #, $, % etc. in our
££ identifier. Identifier can be of any length.
16. what are expressions?
An expression is a combination of values, variables, operators, and calls
to functions. If you type an expression at the Python prompt, the interpreter
evaluates it and displays the result:
>>> 1 + 1=2
17. What is a statement?
A statement is an instruction that the Python interpreter can execute. When
you type a statement on the command line, Python executes it. Statements
don‘t produce any result. For example, a = 1 is an assignment statement. if
statement, for statement, while statement etc. are other kinds of statements.
18. What is multiline statement?
In Python, end of a statement is marked by a newline character. But we
can make a statement extend over multiple lines with the line continuation
character (\).
For example:
a=1+2+3+\
4+5+6+\
7+8+9
Data, Expressions Statements 2.43

19. What is docstring?


Doc string is short for documentation string. It is a string that occurs as the
first statement in a module, function, class, or method definition. It is used to
explain in brief, what a function does.
20. What is a function? Mention the type of function and use.
A Function can be called as a section of a program that is written once and can
be executed whenever required in the program, thus making code reusability.
There are two types of Functions.
a. Built-in Functions: Functions that are predefined. We have used many
predefined functions in Python.
b. User- Defined: Functions that are created according to the requirements.
21. Mention the types of arguments in python
1. python default arguments.
2. python keyword argument
3. python arbitrary argument
22. What is meant by module in python?
A module is a file consisting of Python code. A module can define functions,
classes and variables. A module can also include runnable code.
23. List some built in modules in python
There are many built in modules in Python. Some of them are as follows:math,
random , threading , collections , os , mailbox , string , time , tkinter etc..
24. What is the use of dir() function?
The dir() built-in function returns a sorted list of strings containing the names
defined by a module. The list contains the names of all the modules, variables
and functions that are defined in a module.
25. What operators does python support?
££ Arithmetic Operators
££ Comparison (Relational) Operators
££ Assignment Operator
££ Logical Operators
££ Bitwise Operators
££ Membership Operators
££ Identity Operator
2. 44 Problem Solving and Python Programming

26. What is an Arithmetic operator?


Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication etc.
The operators are: +,-,/,%,*,**
27. What is the use of comparison operator?
Comparison operators are used to compare values. It either returns True or
False according to the condition.
>,<,>=,<=,==,!=
28. What are logical operators and Bitwise operators?
Logical operators are the and, or, not operators. Bitwise operators act on
operands as if they were string of binary digits. It operates bit by bit, hence the
name.
The operators are:&,|,`^,>>,<<
29. What are assignment statements?
Assignment operators are used in Python to assign values to variables.a = 5
is a simple assignment operator that assigns the value 5 on the right to the
variable a on the left.
30. Mention the features of 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.
31. Give the characteristics of membership operator?
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).In a dictionary we can only test for presence of key, not the value.
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

2. 2
Review Questions
1. Explain the data types in python
2. Ilustrate interpreter and interactive mode in python with example. 3.Explain
Data, Expressions Statements 2.45

function and module with suitable example


4. Write short notes on types of operators in python with appropriate example
5. Explain briefly constant, variables, expression, keywords and statements
available in python 6.Write the following python programs.
a. Exchange the value of two v b.Circulate the value of n variables
b. Test whether a given year is leap year or not
c. to find the sum of n natural numbers
d. To find whether a given number is Armstrong number or not f. To print
Fibonacci series
e. To find factorial of a given number
f. To convert Celsius to Fahrenheit

You might also like