You are on page 1of 34

1

UNIT II DATA, EXPRESSIONS, STATEMENTS

Python interpreter and interactive mode; values and types: int, float, boolean, string, and
list; variables, expressions, statements, tuple assignment, precedence of operators,
comments; modules and functions, function definition and use, flow of execution,
parameters and arguments; Illustrative programs: exchange the values of two variables,
circulate the values of n variables, distance between two points.

Introduction
Programming:
Program: A program is a sequence of instructions that specifies how to perform a
computation. The computation might be something mathematical, such as solving a
system of equations or finding the roots of a polynomial, but it can also be a symbolic
computation, such as searching and replacing text in a document or something graphical,
like processing an image or playing a video.
There are few basic instructions appear in every programming language:
 input: Get data from the keyboard, a file, or some other device.
 output: Display data on the screen or send data to a file or other device.
 math: Perform basic mathematical operations like addition and multiplication.
 conditional execution: Check for certain conditions and execute the appropriate
code.
 repetition: Perform some action repeatedly, usually with some variation.
Characteristics of a Good Program: The following important characteristics should be
followed while writing a program.
 Accuracy
 Clarity
 Efficiency
 Modularity
 User Friendly
 Reliable
 Portable

Programming language:
High-level languages are much easier to write and more problem oriented. Low-
level languages sometimes referred to as “machine languages” or “assembly languages.
Compiler is the software used to translate a complete program written in a high level
language into low level language. The high-level program is called the source code, and
the translated program is called the object code or the executable. Once a program is
compiled, we can execute it repeatedly without further translation. Interpreter is also
software; it reads the source code line by line and converts them into object code.

 Bug: An error in a program.


 Debugging: The process of finding and removing any of the three kinds of
programming errors.

Mr. P. J. Merbin Jose


2

 Syntax: The structure of a program.


 Syntax error: An error in a program that makes it impossible to parse (and
therefore impossible to interpret).
 Exception: An error that is detected while the program is running.
 Semantics: The meaning of a program
 Semantic error: An error in a program that makes it do something other than
what the programmer intended

PYTHON:
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. It was created by Guido van Rossum at National Research
Institute for Mathematics and Computer Science in Netherlands during 1985- 1990.
Python got its name from “Monty Python‟s flying circus”, which is a British comedy
series. Python was released in the year 2000.

Features:
 Python is interpreted: Python is processed at runtime by the interpreter. No need
to compile Python program before executing it.
 Python is Interactive: We can use Python prompt and interact with the interpreter
directly to write our programs.
 Python is Object-Oriented: Python supports Object-Oriented style or technique
of programming that encapsulates code within objects.
 Python is a Beginner's Language: Python is a great language for the beginner-
level programmers and supports the development of a wide range of applications.
 Easy-to-learn: Python is clearly defined and easily readable. The structure of the
program is very simple. It uses few keywords.
 Easy-to-maintain: Python's source code is fair.
 Portable: Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
 Interpreted: Python is processed at runtime by the interpreter. So, there is no
need to compile a program before executing it. We can simply run the program.
 Extensible: Programmers can embed python within their C, C++, Java script,
ActiveX, etc.
 Free and Open Source: Anyone can freely distribute it, read the source code, and
edit it.
 High Level Language: When writing programs, programmers concentrate on
solutions of the current problem, no need to worry about the low level details.
 Scalable: Python provides a better structure and support for large programs than
shell scripting.

Application:
 Embedded scripting language
 3D software
 Web Development
 Image processing and graphic Design Application
 GUI based desktop application
 Science and Computational application
 Games

Mr. P. J. Merbin Jose


3

 Enterprise and business applications


 Operating System
 Language Development
 Prototyping
 Network Programming
Companies Used:
 Bit Torrent file sharing
 Google search engine, Youtube
 Intel, Cisco, HP, IBM
 i–Robot
 NASA
 Facebook, Drop box, etc.,

2.1. PYTHON INTERPRETER AND INTERACTIVE MODE:


Interpreter: To execute a program in a high-level language by translating it one line at a
time.
Compiler: To translate a program written in a high-level language into a low-level
language all at once, in preparation for later execution.
Python is an example of a high-level language; some of the other high-level
languages are C, C++, Perl, and Java. Programs written in a high-level language have to
be processed before they can run. Python is considered an interpreted language because
Python programs are executed by an interpreter.

Advantages of python:
 Readability: If the software has a highly readable code, then it is easier to
maintain.
 Portability: Platform independent.
 Vast support of libraries: It has large collection of in-built functionalities.
 Software integration: It can easily extend, communicate and integrate with other
languages.
 Developer productivity: It is a dynamically typed language i.e., no need to declare
variables explicitly.
 Python programs run immediately i.e., without taking much time to link and
compile.
IDLE: Integrated Development and Learning Environment.
The IDLE tool is included in python‟s installation package. It offers more efficient
platform for write code and work interactively with python. We can access IDLE on the
same folder or command line icon or on the start menu. By clicking on the IDLE icon, it
displays the python shell window. It comprises of python shell (allows users to access
different features of IDLE through its drop down menu) and python editor (allows us to
work in script mode).
Features of IDLE:
 Multi-window text editor with syntax highlighting.

Mr. P. J. Merbin Jose


4

 Auto completion with smart indentation.


 Python shell to display output with syntax highlighting.

Python Interpreter: It is a program that reads and executes Python code. It uses 2
modes of Execution.
1. Interactive mode
2. Script mode

1. Interactive mode: Interactive Mode, as the name suggests, allows us to interact with
OS.
When we type Python statement, interpreter displays the result(s) immediately.
Eg: >>> 1 + 1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for us to
enter code. If we type 1 + 1, the interpreter replies 2.

Eg: >>> print ('Hello, World!')


Hello, World!
Advantages:
 Python, in interactive mode, is good enough to learn; experiment or explore.
 Working in interactive mode is convenient for beginners and for testing small
pieces of code.
Drawback:
We cannot save the statements and have to retype all the statements once again to re-run
them.

2. Script mode: In script mode, we type python program in a file and then use interpreter
to execute the content of the file. Scripts can be saved to disk for future use. Python
scripts have the extension .py (meaning that the filename ends with .py).
We can save the code with filename.py and run the interpreter in script mode to execute
the script.
In a file filename.py
Print(1) Output
x=2 >>>1
print(x) 2

Interactive mode Script mode


A way of using the Python interpreter by A way of using the Python interpreter to
typing commands and expressions at the read and execute statements in a script
prompt
Can‟t save and edit the code Can save and edit the code
If we want to experiment with the code, If we are very clear about the code, we can
We can use interactive mode. use script mode.
We cannot save the statements for further We can save the statements for further use

Mr. P. J. Merbin Jose


5

use and we have to retype all the statements and we no need to retype all the statements
to re-run them. to re-run them.
We can see the results immediately. We can‟t see the results immediately.

2.2. VALUES AND TYPES


Programming languages contain data in terms of input and output and any kind of
data can be presented in terms of value.
Values
A value is one of the basic things of a program. There are different values integers, float
and strings. The numbers with a decimal point belong to a type called float. The values
written in quotes will be considered as string, even it‟s an integer. If type of value is not
known it can be interpreted as an in-built method called type.
Syntax to know the type of any value is
type(value)
Eg:

>>>type('Hello,
World!') <type 'str'>

>>>type(17)
<type 'int'>
>>>type('17')
<type 'str'>
>>>type('3.2')
<type 'str'>

Data types in Python:


Every value in Python has a data type. It is a set of values, and the allowable
operations on those values. In Python programming, data types are actually classes and
variables are instance (object) of these classes.

 Numbers:
Number data type stores Numerical Values. This data type is immutable [i.e.
values/items cannot be changed]. Python supports integers, floating point numbers and
complex numbers. They are defined as,
Mr. P. J. Merbin Jose
6

Integers Float Complex

Integer is a It consists of a whole They are of the


combination of number, decimal point form a+bj where a
positive and and fractional part. and b are floats
and j represents
negative numbers
the square root of
including zero. The float function
-1(which is an
In a program, converts a string into a imaginary
integer literals are floating point number. number)
written without >>>float(‟34.78‟)
commas and a 34.78 The real part of
leading minus sign the number is a
and the imaginary
to indicate a
part of the number
negative value. is b
The int function
converts a string or
a number into a
whole number
>>>int(23.56)
23
>>>int(„145‟)
145
Ex: 28 Ex:32.45 Ex: 3+7j
>>>17 >>>8.3e1 >>>2+3j
17 83.0 (2+3j)
>>>-23
-23

Boolean
It has values either True or False. Internally true value represented as 1 and false as 0. It
is used to compare two values.
Eg:
>>>4==8
False
>>>4<8
True

Sequence:
A sequence is an ordered collection of items, indexed by positive integers. It is a
combination of mutable (value can be changed) and immutable (values cannot be
changed) data types.
There are three types of sequence data type available in Python, they are
7

1. String
2. List
3. Tuple
String
A String in Python consists of a series or sequence of characters - letters, numbers, and
special characters. Strings are marked by quotes:
 single quotes (' ') Eg, 'This a string in single quotes'
 double quotes (" ") Eg, "'This a string in double quotes'"
 triple quotes (""" """) Eg, This is a paragraph. It is made up of multiple lines and
sentences.""”
Individual character in a string is accessed using a subscript (index). Characters can
be accessed using indexing and slicing operations. Strings are immutable i.e. the contents
of the string cannot be changed after it is created.
String is sequence of Unicode characters. We can use single quotes or double quotes
to represent strings. Multi-line strings can be denoted using triple quotes, ''' or """.
Eg:
>>> s = "This is a string"
>>> s = „‟‟a multiline‟‟‟
The str function is used to convert a number into a string.
>>>str(34.23)
‟34.23‟
List
 List is an ordered sequence of items. Values in the list are called elements / items.
 It can be written as a list of comma-separated items (values) between square
brackets [ ].
 Items in the lists can be of different data types.
Eg:
>>> a = [‟spam‟, ‟eggs‟, 100, 1234]
>>> a
Output: [‟spam‟, ‟eggs‟, 100, 1234]
We can use a list‟s constructor to create a list.
Create an empty list L1=list()
Create a list with any integers L2=list([3,5,2])
Create a list using built-in range L3=list(range(0,5)). Creates a list with elements from 0
to 5.
Tuple:
A tuple is same as list, except that the set of elements is enclosed in parentheses instead
of square brackets.
8

A tuple is an immutable list. i.e., once a tuple has been created, we can't add elements
to a tuple or remove elements from the tuple.
Benefit of Tuple:
 Tuples are faster than lists.
 If the user wants to protect the data from accidental changes, tuple can be used.
 Tuples can be used as keys in dictionaries, while lists can't.
Eg:
Tuple with string values
>>>T= („sun‟,‟mon‟,‟tue‟)
>>>print T
(„sun‟,‟mon‟,‟tue‟)

Tuple with single character


>>>T= („P,‟‟Y‟,‟T‟,‟H‟,‟O‟,‟N‟)
Print T
(„P,‟‟Y‟,‟T‟,‟H‟,‟O‟,‟N‟)
Sets:
A set is an unordered collection of items. Every element is unique and cannot be
changed. A set is created by placing all the items (elements) inside curly braces{},
separated by comma.
Eg:
>>> x=set("PYTHON PROGRAMMING")
>>> print(x)
set(['N', 'M', 'H', 'P', 'R', 'I', 'T', 'O', 'G', 'Y', 'A', ' '])
>>> a={5,2,3,1,4}
>>> print(a)
set([1, 2, 3, 4, 5])
>>> print(type(a))
<class 'set'>
>>> b=set([5,7,3,9,7,2,9,1])
>>>print(b)
set([1,2,3,5,7,9])

Dictionaries:
Lists are ordered sets of objects, whereas dictionaries are unordered sets.
 Dictionary is created by using curly brackets. i,e. {}
 Dictionaries are accessed via keys and not via their position.
 A dictionary is an associative array (also known as hashes). Any key of the
dictionary is associated (or mapped) to a value.
 The values of a dictionary can be any Python data type. So dictionaries are
unordered key-value-pairs(The association of a key and a value is called a key-
value pair )
 Dictionaries don't support the sequence operation of the sequence data types like
strings, tuples and lists.
Eg:
9

>>> food = {"ham":"yes", "egg" : "yes", "rate":450 }


>>>print(food)
{'rate': 450, 'egg': 'yes', 'ham': 'yes'}

We can access the item only with keys


>>>>print(food["rate"])
450

2.3 VARIABLES, EXPRESSIONS AND STATEMENTS


Python Identifiers
In Python, identifier is the name given to entities like class, functions, variables
etc., It helps differentiating one entity from another.

Rules for writing identifiers


1. 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.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is
perfectly fine.
3. Keywords cannot be used as identifiers.
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.
5. Identifier can be of any length.

Variables
A variable is a name that refers to a value. A variable is a location in memory used
to store some data (value). They are given unique names to differentiate between
different memory locations. The assignment operator (=) to assign values to a variable.
An assignment statement creates new variables and gives them values:
Rules for naming variables:
 Variable names can be uppercase letters or lower case letters.
 Variable names can be at any length
 They can contain both letters and numbers, but they can‟t begin with a
number.
 The underscore ( _ ) character can appear in a name. It is often used in
names with multiple words.
Eg:my_name
 No blank spaces are allowed between variable name.
 A variable name cannot be any one of the keywords or special characters.
 Variable names are case-sensitive
Assigning value to variable:
Value should be given on the right side of assignment operator(=) and variable on left
side.
10

>>> message = „something‟


>>> n = 17
>>> pi = 3.1415926535897932
The type of a variable is the type of the value it refers to.
Eg:
>>> type(n)
<type 'int'>
Assigning a single value to several variables simultaneously:
>>> a=b=c=100
>>> print(a,b,c)
100 100 100
Assigning multiple values to multiple variables:
>>> a,b,c=10,12.5,"ABC"
>>> print(a,b,c)
10 12.5 ABC
If we give an illegal name to a variable, we get a syntax error.
Eg: 76trom = 'big parade'
Syntax Error: invalid syntax
Keywords: The interpreter uses keywords to recognize the structure of the program, and
they cannot be used as variable names. Python 2 has 31 keywords. Python 3 has 33
keywords.
and del from not while
as elif global or with
assert else if pass False
break except import print True
class exec in raise yield
continue finally is return
def for lambda try
Expressions and statements
An expression is a combination of values, variables, and operators. A value all by itself
is considered an expression, and also a variable. So the following are all legal
expressions:
Eg:
>>> 42
42
11

>>> a=2
>>> a+3+2
7
>>> z=("hi"+"friend")
>>> print(z)
hifriend

Statements:
Instructions that a Python interpreter can execute are called statements. A
statement is a unit of code that the Python interpreter can execute. Two kinds of
statement: print and assignment.
Eg:
>>> n = 17
>>> print(n)
Here, 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.
Eg:
a=1+2+3+\
4+5+6+\
7+8+9
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 (\).
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a
block of code. Python uses indentation.

A code block (body of a function, loop etc.) starts with indentation and ends with
the first unindented line. The amount of indentation is up to you, but it must be consistent
throughout that block. Generally four whitespaces are used for indentation and is
preferred over tabs. Here is an example.

Python Tuple
Tuple is an ordered sequence of items same as list. The only difference is that
tuples are immutable. Tuples once created cannot be modified.
12

Tuples are used to write-protect data and are usually faster than list as it cannot
change dynamically. It is defined within parentheses () where items are separated by
commas.
Eg:
>>> t = (5,'program', 1+3j)
>>> a=(5,7.9,10)

Tuple assignment
 An assignment to all of the elements in a tuple using a single assignment
statement.
 Python has a very powerful tuple assignment feature that allows a tuple of
variables on the left of an assignment to be assigned values from a tuple on the
right of the assignment.
 The left side is a tuple of variables; the right side is a tuple of values.
 Each value is assigned to its respective variable.
 All the expressions on the right side are evaluated before any of the assignments.
This feature makes tuple assignment quite versatile.
 Naturally, the number of variables on the left and the number of values on the
right have to be the same.

Examples:
>>> T1=(10,20,30)
>>> T2=(100,200,300,400)
>>>print T1
(10,20,30)
>>>print T2
(100,200,300,400)
>>>T1,T2=T2,T1
>>>print T1
(100,200,300,400)
>>>Print T2
(10,20,30)

One way to think of tuple assignment is as tuple packing/unpacking.


In tuple packing, the values on the left are „packed‟ together in a tuple:
>>> b = ("George", 25, "20000") # tuple packing
In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the
variables/names on the right:
>>> b = ("George", 25, "20000") # tuple packing
>>> (name, age, salary) = b # tuple unpacking
>>> name
13

'George'
>>> age
25
>>> salary
'20000'
The right side can be any kind of sequence (string, list, tuple)
>>> (a, b, c, d) = (1, 2, 3)
ValueError: need more than 3 values to unpack
Comments
Comments indicate Information in a program that is meant for other programmers
(or anyone reading the source code) and has no effect on the execution of the program. In
Python, we use the hash (#) symbol to start writing a comment.
Eg:
#This is a comment
#print out Hello
print('Hello')
Input and output
INPUT: Input is data entered by user (end user) in the program. In python, input ()
function is available for input.

Syntax for input() is:


variable = input (“data”)
>>> x=input("enter the name:")
enter the name: george
>>>y=int(input("enter the number"))
enter the number 3

Python accepts string as default data type. Conversion may require for all other types.

OUTPUT: Output can be displayed to the user using print statement.

Syntax:
print (expression/constant/variable)

print (“Statement”,variable_name)

print (“Statement %formatting function”%variable_name)


After all values are printed, it defaults into a new line.
The file is the object where the values are printed and its default value is sys.stdout.
Example:
>>> print ("Hello")
Hello
14

PRECEDENCE OFOPERATORS
OPERATORS:
An operator is a symbol that represents an operation performed on one or more operands.
An operand is a quantity on which an operation is performed.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator.

Types of Operators:
Python language supports the following types of operators
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

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
- Subtract right operand from the left or unary minus x-y
* 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 x % y
the right
// Floor division – division of operands where the result is x//y
the quotient in which the digits after the decimal points
are removed.
** Exponent - left operand raised to the power of right x**y

Example: Arithmetic operators in Python


x = 15
y=4
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)

# Output: x ** y = 50625
print('x ** y =',x**y)
15

Examples Output:
a=10 a+b= 15
b=5 a-b= 5
print("a+b=",a+b) a*b= 50
print("a-b=",a-b) a/b= 2.0
print("a*b=",a*b) a%b= 0
print("a/b=",a/b) a//b= 2
print("a%b=",a%b) a**b= 100000
print("a//b=",a//b)
print("a**b=",a**b)

Comparison operators: Comparison operators are used to compare values. It either


returns True or False according to the condition.
Operator Meaning Example
Greater than - True if left operand is greater than the x>y
> right
< Less than - 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 x<=y
<= or equal to the right

Example Output:
a=10 a>b=> True
b=5 a>b=> False
print("a>b=>",a>b) a==b=> False
print("a<b=>",a<b) a!=b=> True
print("a==b=>",a==b) a>=b=> False
print("a!=b=>",a!=b) a>=b=> True
print("a<=b=>",a<=b)
print("a>=b=>",a>=b)

Logical operators: Logical operators are used to compare and evaluate logical
operations. Python supports three logical operators: and, or, not

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,y=10,10
16

print((x>=y) and (x==y))


x=11
y=5
print((x>y) and (y>x))
print((x>y) or (y>x))
print(not(x>y))
Output
True # (10>=10)(true) and (10==10) (true) so it returns true
False # (10>5) (true) and (5>10) (false) so it returns false
True #(10>5) (true) or (5 is not >10) (false) so it returns true.
False # not(10>5), not true is false

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 the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Operato Meaning Example
r
& 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 Output
a = 60 # 60 = 00111100 Line 1 - Value of c is 12
b = 13 # 13 = 0000 1101 Line 2 - Value of c is 61
c=0 Line3 - Value of c is 49
c=a&b #12= 0000 1100 Line 4 -Value of c is -61
print "Line 1 - Value of c is ", c Line 5- Value of c is 240
Line 6 - Value of c is 15
c = a | b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c

c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c

c=~a #-61=1100 0011


17

print "Line 4 - Value of c is ", c

c = a << 2; # 240 = 1111 0000


print "Line 5 - Value of c is ", c

c = a >> 2; # 15 = 0000 1111


print "Line 6 - Value of c is ", c

Assignment operators
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.
There are various compound operators in Python like a += 5 that adds to the
variable and later assigns the same. It is equivalent to a = a + 5.
Operator Description Example
= Assigns values from right side c = a + b Assigns
operands to left side operand value of a+ b into c

+= It adds right operand to the left c += a is


operand and assign equivalent
the result to left operand to c = c + a
-= It subtracts right operand from the c -= a is
left operand and equivalent
assign the result to left operand to c = c - a

*= It multiplies right operand with the c *= a is


left operand and equivalent
assign the result to left operand to c = c * a

/= It divides left operand with the c /= a is


right operand and equivalent
assign the result to left operand to c = c / ac
/= a is
equivalent
to c = c / a
%= It takes modulus using two c %= a is
operands and assign the equivalent
result to left operand to c = c % a
**= Performs exponential (power) c **= a is
calculation on equivalent
operators and assign value to the to c = c ** a
left operand
//= It performs floor division on c //= a is
operators and assign equivalent
value to the left operand to c = c //a
18

Example
a = 21
b = 10
c=0
c=a+b
print("Line 1 - Value of c is ", c)
c += a
print("Line 2 - Value of c is ", c)
c *= a
print("Line 3 - Value of c is ", c)
c /= a
print("Line 4 - Value of c is ", c)
c = 2 c %= a
print("Line 5 - Value of c is ", c) c **= a
print("Line 6 - Value of c is ", c) c //= a
print("Line 7 - Value of c is ", c)
Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864

Special operators: Python language offers some special type of operators like the
identity operator or the membership operator.
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.
Operator Meaning
is True if the operands are identical(refer to the same object)
is not True if the operands are not identical(do not refer to the
same object)

Example: Identity operators in Python


x1 = 5
y1 = 5
x2 = 'Hello'
19

y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
# Output: False
print(x1 is not y1)
# Output: True
print(x2 is y2)

# Output: False
print(x3 is y3)

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.
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).
In a dictionary we can only test for presence of key, not the value.
Operator Meaning Example
In True if value/variable is 5 in x
found in the sequence
not in True if value/variable is not 5 not in x
found in the sequence

Example: Membership operators in Python


x = 'Hello world'
y = {1:'a',2:'b'}
# Output: True
print('H' in x)

# Output: True
print('hello' not in x)
# Output: True
print(1 in y)
# Output: False
print('a' in y)
Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive).
Similarly, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False.
20

Precedence of Operators
The order of evaluation depends on the rules of precedence. The acronym
PEMDAS is a useful way to remember the rules:

Parentheses have the highest precedence


Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is
3,not 27.
Multiplication and Division have the same precedence, which is higher than Addition
and Subtraction, which also have the same precedence. So 2*3-1 is 5, not 4, and 6+4/2 is
8, not 5.
Operators with the same precedence are evaluated from left to right
Operator precedence in python
Sl.No Operator Description
1. ** Exponentiation(raise to the power)
2. ~, + ,- Complement, unary plus, and minus
3. * , /, %, // Multiply, divide, modulus, and floor division
4. +,- Addition and subtraction
5. << ,>> Right and left bitwise shift
6 & Bitwise „AND‟
7. ^ ,| Bitwise exclusive „OR‟ and regular „OR‟
8. <=,< >,>= Comparison operator
9. == , != Equality operators
10 =%,=/,=//,=,=+,=*,=** Assignment operators
11. not Logical operator not
12 and Logical operator and
13 or Logical operator or

Examples:
A=9-12/3+3*2-1 A=2*3+4%5-3/2+6 find m=?
a=? A=6+4%5-3/2+6 m=-43||8&&0||-2
a=9-4+3*2-1 A=6+4-3/2+6 m=-43||0||-2
a=9-4+6-1 A=6+4-1+6 m=1||-2
a=5+6-1 A=10-1+6 m=1
a=11-1 A=9+6
a=10 A=15
a=2,b=12,c=1 a=2,b=12,c=1 a=2*3+4%5-3//2+6
d=a<b>c d=a<b>c-1 a=6+4-1+6
d=2<12>1 d=2<12>1-1 a=10-1+6
d=1>1 d=2<12>0 a=15
d=0 d=1>0
d=1
21

Modules and Functions


Modules:
A module is a file containing Python definitions, functions, statements and instructions.
Standard library of Python is extended as modules. To use these modules in a program,
programmer needs to import the module. A module is file that contains some predefined
python codes.

Once we import a module, we can reference or use to any of its functions or variables in
our code.
 There is large number of standard modules available in python.
 Standard modules can be imported the same way as we import our user- defined
modules.
 Every module contains many functions.
To access one of the functions, we have to specify the name of the module and the name
of the function separated by dot. This format is called dot notation.
Syntax:
import module_name
module_name.function_name(variable)
• Example:
Importing Built_in Module Output
import math 5.0
x=math.sqrt(25)
print(x)
There are four ways to import a module in a program
import: It is simplest and most commonfrom import: It is used to get a specific
way to use modules in our code function in the code instead of complete
Example: file.
import math Example:
x=math.pi from math import pi
print("The value of pi is",x) x= pi
Output print("The value of pi is",x)
The value of pi is 3.141592653589793 Output
The value of pi is 3.141592653589793
import with renaming: we can import a import all: we can import all
module by renaming the module as our names(definitions) form a module using *
wish Example:
Example: from math import *
import math as m x= pi
x=m.pi print("The value of pi is",x)
print("The value of pi is",x) Output
Output The value of pi is 3.141592653589793
The value of pi is 3.141592653589793
22

Functions
Function is a sub program which consists of set of instructions used to perform a specific
task. A large program is divided into basic building blocks called function.
Need for Function:
• When the program is too complex and large they are divided into parts. Each part
is separately coded and combined into single program. Each subprogram is called
as function.
• Debugging, Testing and maintenance becomes easy when the program is divided
into subprograms.
• Functions are used to avoid rewriting same code again and again in a program.
• Function provides code re-usability
• The length of the program is reduced.
Types of function:
Functions can be classified into two categories:
1. User_defined function
2. Built_in function
 Built in functions
Built in functions are the predefined functions i.e., already created and stored in
python.These built in functions are always available for usage and accessed by a
programmer. It cannot be modified. Some of the built in functions in python are abs(),
float(), help(), format(), input(), print() etc.,
• >>> max(5,2)
5
• >>> float(3)
3.0
• >>> min(8,9)
8
 Type conversion
There are some built in functions in the python programming languages that can be
convert one type of data into another type. For example int(), float(), str()

Example:
int functions can take any number value and convert it into an integer
>>> int(4.7)
4
In this example a floating point number 4.7 that was converted to an integer number4 by
the int function

>>> int('college')
Trace back (most recent call last):
File "<pyshell#2>", line 1, in <module>
23

int('college')
Value Error: invalid literal for int() with base 10: 'college'
In this example a string was not a number and applied int function to it, got an error.
This means that a string is not a number so it cannot be converted to an integer.

 Type Coercion
Implicit conversion is also known as type coercion, and is automatically done by the
interpreter. Type coercion is a process through which the python interpreter
automatically converts a value of one type into a value of another type according to the
requirement.
Example:
minute=59
>>> minute/60.0
0.9833333333333333
In this example we make the denominator a float number. The python interpreter
automatically converts the numerator into float and does the calculation.
 Mathematical function
1. math
Python provides a math module that contains most of the familiar and important
mathematical functions.
Example:
>>> import math
>>> math.sqrt(4)
2.0
2. Date and Time
Python provides the built in modules time and calendar through which we can handle
date and time in several ways. For this we have to import time and calendar module.
>>> import calendar
>>> c=calendar.month(2019,9)
>>> print(c)
September 2019
Mo Tu We Th Fr Sa Su
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
24

3.help()
It is used to invoke the help system. It takes an object as an argument. It gives all the
detailed information about that objects.
>>> import math
>>> help(math.sin)

Help on built-in function sin in module math:


sin(x, /)

Return the sine of x (measured in radians).


Some more built-in functions are given below:
Function Description
>>>max(3,4) # returns largest element
4
>>>min(3,4) # returns smallest element
3
>>>len("hello") #returns length of an object
5
>>>range(2,8,1) #returns range of given values
[2, 3, 4, 5, 6, 7]
>>>round(7.8) #returns rounded integer of the given number
8.0
>>>float(5) #returns float number from string or integer
5.0
>>>int(5.0) # returns integer from string or float
5
>>>pow(3,5) #returns power of given number
243
>>>type( 5.6) #returns data type of object to which it belongs
<type 'float'>
>>>t=tuple([4,6.0,7]) # to create tuple of items from list
(4, 6.0, 7)
>>>print("good # displays the given object
morning")
Good morning
>>>input("enter name: # reads and returns the given string
")
enter name : George

User Defined Functions:


User defined functions are the functions that programmers create for their
requirement and use. i.e., User defined functions are defined by programmers at the time
of writing programs. User can understand the internal working of the function. These
functions can then be combined to form module which can be used in other programs
by importing them.
25

Advantages of user defined functions


• Programmers working on large project can divide the workload by making
different functions.
• If repeated code occurs in a program, function can be used to include those codes
and execute when needed by calling that function.
Elements of User defined functions
In python the user defined functions contain two elements. They are:
1. Function definition
2. Function call
Function Definition:
A function definition specifies the name of a new function and the sequence of
statements that run when the function is called.
Syntax:
def name_of_function (list of formal parameters):
body of function
For example, we could define the function max by the code
def max(x, y):
if x > y:
return x
else:
return y
Here, def is a reserved word that tells Python that a function is about to be defined.
A function definition consists of following components.
 Keyword def marks the start of function header.
 A function name to uniquely identify it. Function naming follows the same
rules of writing identifiers in Python.
 Parameters (arguments) through which we pass values to a function. They
are optional.
 A colon (:) to mark the end of function header.
 Optional documentation string (docstring) to describe what the function does. Eg.
```multi line comments```
 One or more valid python statements that make up the function body.
Statements must have same indentation level (usually 4 spaces).
 An optional return statement to return a value from the function.

Function Call: 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.
>>>type(32)
26

<type 'int'>
The name of the function is type. The expression in parentheses is called the
argument of the function. The result is called the return value.
The return statement
The return statement is used to exit a function and go back to the place from where
it was called. The Syntax of return statement:
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.
For example:
>>> print(greet("May")) Hello, May. Good morning! None
Here, None is the returned value

Example:
Swapping two variables using function
def swap(a,b):
a,b=b,a
print("After Swap:")
print("First number:",a)
print("Second number:",b)
a=input("\n Enter the first number")
b=input("\n Enter the second number")
print("Before Swap:")
print("First number:",a)
print("Second number:",b)
swap(a,b)
Output:
Enter the first number30
27

Enter the second number50


Before Swap:
First number: 30
Second number: 50
After Swap:
First number: 50
Second number: 30
Flow of execution
The order in which statements are executed is called the flow of execution.
Execution always begins at the first statement of the program. Statements are executed
one at a time, in order from top to bottom. Function definitions do not alter the flow of
execution of the program, but remember that statements inside the function are not
executed until the function is called.
• Function calls are like a bypass in the flow of execution. Instead of going to the
next statement, the flow jumps to the first line of the called function, executes all
the statements there, and then comes back to pick up where it left off.
Function Prototypes:
• Function with arguments and with return type
• Function without arguments and without return type
• Function with arguments and without return type
• Function without arguments and with return type
Without argument, Without Return With argument, Without Return Type
Type
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enter b")) print(c)
c=a+b a=int(input("enter a"))
print(c) b=int(input("enter b"))
add() add(a,b)
o/p: o/p:
enter a 10 enter a 10
enter b 89 enter b 89
99 99
Without argument, With return type With argument, With return type
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enter b")) reurn c
c=a+b a=int(input("enter a"))
return c b=int(input("enter b"))
c=add() c=add(a,b)
print(c) print(c)
28

o/p: o/p:
enter a 10 enter a 10
enter b 89 enter b 89
99 99
Parameters and Arguments
Parameters:
• Parameters are the value(s) provided in the parenthesis when we write function
header.
• These are the values required by function to work.
• If there is more than one value required, all of them will be listed in parameter list
separated by comma.
• Example: def add(a,b):
Arguments:
• Arguments are the value(s) provided in function call/invoke statement.
• List of arguments should be supplied in same way as parameters are listed.
• Bounding of parameters to arguments is done 1:1, and so there should be same
number and type of arguments as mentioned in parameter list.
• Example: add(x,y)
Illustrative Programs
1. Exchange the values of two variables (or) Swapping Output
of values
x=input(“Enter value of x:‟) Enter value of x: 55
y= input(“Enter value of y:‟) Enter value of y: 84
temp=x
x=y The value of x after swapping:84
y=temp The value of y after swapping:55
print(“ The value of x after swapping:”,x)
print(“ The value of y after swapping:”,y)

2.i Circulate the values of n variables(list) Output


a=list(input("enter the list")) enter the list '1234'
print(a) ['1', '2', '3', '4']
for i in range(1,len(a),1): ['2', '3', '4', '1']
print(a[i:]+a[:i]) ['3', '4', '1', '2']
['4', '1', '2', '3']

2.ii. Circulate the numbers using list with user Output:


defined function.
def circulate():
for val in range(0,no_of_terms,1):
Enter number of values : 5
Enter integer : 3
29

ele = list1.pop(0) Enter integer : 0


Enter integer : 9
list1.append(ele)
Enter integer : 4
print(list1) Enter integer : 5
('Circulating the elements of list ',
no_of_terms = int(input("Enter number of values : "))
[3, 0, 9, 4, 5])
list1 = [] [0, 9, 4, 5, 3]
[9, 4, 5, 3, 0]
for val in range(0,no_of_terms,1):
[4, 5, 3, 0, 9]
ele = int(input("Enter integer : ")) [5, 3, 0, 9, 4]
[3, 0, 9, 4, 5]
list1.append(ele)
print("Circulating the elements of list ", list1)
circulate()
2.iii Circulate the values of n variables(function)
def circulate(A,N): Output
for i in range (0,N): Enter n: 5
j=len(A)-1 Circulation 1=[5,1,2,3,4]
while j>0: Circulation 2=[4,5,1,2,3]
temp=A[j] Circulation 3=[3,4,5,1,2]
A[j]=A[j-1] Circulation 4=[2,3,4,5,1]
A[j-1]=temp Circulation 5=[1,2,3,4,5]
j=j-1
print („Circulation‟,i+1,‟=‟,A)
return
A=[1,2,3,4,5]
N=input(“Enter n:”)
Circulate(A,n)
3.Finding distance between two points
The formula for distance between two point (x1, y1) and (x2, y2) is

import math Output


x1=input(“Enter the value for x1:”) Enter the value for x1: 7
y1=input(“Enter the value for y1:”) Enter the value for y1: 6
x2=input(“Enter the value for x2:”) Enter the value for x2: 5
y2=input(“Enter the value for y2:”) Enter the value for y2: 7
distance=math.sqrt((x2-x1)**2)+((y2-y1)**2)
print(“The distance between two points:” distance) The distance between two points:2.5
Python Program to calculate the square root Output
num = int(input('Enter a number: ')) Enter a number: 81
num_sqrt = num ** 0.5 The square root of 81 is 9
print('The square root of “,num,” is” ,num_sqrt)
30

Additional programs:
Sl.No Programs Output
1. Python program to swap two variables Enter value of x: 45
(without temporary variable) Enter value of y: 80
# To take input from the user The value of x after swapping: 80
x = input('Enter value of x: ') The value of y after swapping: 45
y = input('Enter value of y: ')
# swap the values without using temporary
variable
x=x+y
y=x–y
x=x-y
print 'The value of x after swapping:‟,x
print 'The value of y after swapping:‟,y

2. Average of three numbers


num1=int(input("Enter a number")) Enter a number45
num2=int(input("Enter a number")) Enter a number50
num3=int(input("Enter a number")) Enter a number100
sum=num1+num2+num3 The average of 45,50,and100is 65.0
avg=sum/3
print("The average of{0},{1},and{2}is
{3}".format(num1,num2,num3,avg))
3. Write a function that draws a grid like the +----+----+
following: | | |
+----+----+ | | |
| | | | | |
| | | | | |
| | | +----+----+
| | | | | |
+----+----+ | | |
| | | | | |
| | | | | |
| | | +----+----+
| | |
+----+----+
def print_border():
print ("+", "- " * 4, "+", "- " * 4, "+")
def print_row():
print ("|", " " * 8, "|", " " * 8, "|")
def block():
print_border()
print_row()
print_row()
print_row()
31

print_row()
block()
block()
print_border()
4 Converting Centigrade to Fahrenheit Enter Celsius:30
C=int(input("Enter celsius:")) 30.0 degree Celsius equal to 86.0
F=C*1.8+32 degree Fahrenheit
print("%0.1f degree Celsius equal to %0.1f
degree Fahrenheit" %(C,F))
5 Converting Fahrenheit to centigrade Enter Fahrenheit 90
F=int(input("Enter Fahrenheit")) 90.0 degree Fahrenheit equal to
C=(F-32)*(5/9) 32.2 degree Celsius
print("%0.1f degree Fahrenheit equal to %0.1f
degree Celsius" %(F,C))
6 Area of a circle Enter Radius 10
from math import pi Area of the circle: 314.1592653589793
r=int(input("Enter Radius"))
area=pi*r*r
print("Area of the circle:",area)

7 Calculating compound interest Enter Principal Amount:3000


P=int(input("Enter Principal Amount:")) Enter rate of interest:9
N=int(input("Enter rate of interest:")) Enter number of Years:12
R=int(input("Enter number of Years:")) Enter time:10
t=int(input("Enter time:")) Compound Interest= 629999.9999999999
CI=P*(1+R/N)*N*t
print("Compound Interest=",CI)

8 Simple calculator function Select operation


def add(a,b): 1.Add
return a+b 2.substract
def substract(a,b): 3.Multiply
return a-b 4.Division
def multiply(a,b): Enter choices(1/2/3/4):1
return a*b Enter first number:34
def divide(a,b): Enter second number:56
return a/b 34 + 56 = 90
print("Select operation") Select operation
print("1.Add") 1.Add
print("2.substract") 2.substract
print("3.Multiply") 3.Multiply
print("4.Division") 4.Division
choice=input("Enter choices(1/2/3/4):") Enter choices(1/2/3/4):2
num1=int(input("Enter first number:")) Enter first number:23
num2=int(input("Enter second number:")) Enter second number:12
if choice=='1': 23 - 12 = 11
print(num1,"+",num2,"=",add(num1,num2)) Select operation
elif choice=='2': 1.Add
32

print(num1,"- 2.substract
",num2,"=",substract(num1,num2)) 3.Multiply
elif choice=='3': 4.Division
Enter choices(1/2/3/4):3
print(num1,"*",num2,"=",multiply(num1,num2)) Enter first number:32
elif choice=='4': Enter second number:12
print(num1,"/",num2,"=",divide(num1,num2))32 * 12 = 384
else: Select operation
print("Invalid input") 1.Add
2.substract
3.Multiply
4.Division
Enter choices(1/2/3/4):4
Enter first number:300
Enter second number:12
300 / 12 = 25.0

9 Getting current date and time Output:


import time; Local current time : Mon Aug 10
localtime = time.asctime( time.localtime(time.time()) 11:11:21 2019
)
print "Local current time :", localtime

10 Leap year or not Output


print("Leap year or not") Leap year or not
year=int(input("Enter year to be checked: ")) Enter year to be checked: 2014
if(year%4==0 and year%100!=0 or year%400==0): The year isn't a leap year
print("The year is a leap year!")
else: Leap year or not
print("The year isn't a leap year") Enter year to be checked: 2004
The year is a leap year!
Part A:
1. What is interpreter?
2. What are the two modes of python?
3. List the features of python.
4. List the applications of python
5. List the difference between interactive and script mode
6. What is value in python?
7. What is identifier? List the rules to name identifier.
8. What is keyword?
9. How to get data types in compile time and runtime?
10. What is indexing and types of indexing?
11. List out the operations on strings.
12. Explain slicing?
13. Explain below operations with the example (i)Concatenation (ii)Repetition
14. Give the difference between list and tuple
33

15. Differentiate Membership and Identity operators.


16. Compose the importance of indentation in python.
17. Evaluate the expression and find the result
(a+b)*c/d
a+b*c/d
18. Write a python program to print „n‟ numbers.
19. Define function and its uses
20. Give the various data types in Python
21. Assess a program to assign and access variables.
22. Select and assign how an input operation was done in python.
23. Discover the difference between logical and bitwise operator.
24. Give the reserved words in Python.
25. Give the operator precedence in python.
26. Define the scope and lifetime of a variable in python.
27. Point out the uses of default arguments in python
28. Generalize the uses of python module.
29. Demonstrate how a function calls another function. Justify your answer.
30. List the syntax for function call with and without arguments.
31. Define recursive function.
32. What are the two parts of function definition? Give the syntax.
33. Point out the difference between recursive and iterative technique.
34. Give the syntax for variable length arguments.

Part B
1. Explain in detail about various data types in Python with an example?
2. Explain the different types of operators in python with an example.
3. Discuss the need and importance of function in python.
4. Explain in details about function prototypes in python.
5. Discuss about the various type of arguments in python.
6. Explain the flow of execution in user defined function with example.
7. Illustrate a program to display different data types using variables and literal constants.
8. Show how an input and output function is performed in python with an example.
9. Explain in detail about the various operators in python with suitable examples.
10. Discuss the difference between tuples and list
11. Discuss the various operation that can be performed on a tuple and Lists (minimum
5)with an example program
12. What is membership and identity operators.
13. Write a program to perform addition, subtraction, multiplication, integer division,
floor division and modulo division on two integer and float.
14. Write a program to convert degree Fahrenheit to Celsius
15. Discuss the need and importance of function in python.
16. Illustrate a program to exchange the value of two variables with temporary variables

Mr. P. J. Merbin Jose


34

17. Briefly discuss in detail about function prototyping in python. With suitable example
program
18. Analyze the difference between local and global variables.
19. Explain with an example program to circulate the values of n variables
20. Analyze with a program to find out the distance between two points using python.
21. Do the Case study and perform the following operation in tuples i) Maxima minima
iii)sum of two tuples iv) duplicate a tuple v)slicing operator vi) obtaining a list from a
tuple vii) Compare two tuples viii)printing two tuples of different data types
22. Write a program to find out the square root of two numbers

Mr. P. J. Merbin Jose

You might also like