Des, Expression
Chapter 2
DATA TYPES, EXPRE
SIONS, STATEMENTS
2.1 PYTHON INTERPRETER AND INTERACTIVE MODE
jon has two basic modes: interpreter and interactive modes.
The interpreter mode is the mode where the scripted and finished .py files»
are run in the Python interpreter. :
The interactive mode is a command line shell which gives immediate
feedback for each statement, fed in the active memory. As new lines are fed
into the interpreter, the fed program is evaluated bot
fh in part and in whole.
2.1.1 Python Interpreter mode |
_ The Python interpreter is a program that reads-and executes Python code, in which
Python ‘statements c:
on statements can be stored in a file. The Python system reads and executes the
commands from the file, rather than from the console. Such a file is termed as
‘Python program. —
Depending on the «
it, start the interpreter by clicking on an icon, or by
typing python on a command line, When it starts, the output will be shown in
Fig. 2.1.
[LB Preen 5 Shc ae os
|[ Fie _Eat_Shel_Debug “Options Window Help
[[eyenon 3.6.0 (v3.6-0:41427
jail, Dec 23 2016, 07:18:10) (HSC v.1900 32 bit (In ~
vel)} on wins2
Type "copyright", "credits" or “license()" for more information.
>>> |m
[> Eares Qa not Sy
Fig. 2.1 Python Interpreter Window
° The first three lines contain information about the interpreter and. the
operating system it is running on.
° They on number is 3.6.0. It begins with 3, if the version is Python 3.1
_ begins with 2, if the version is Python 2.tex that the interprey
ode and bits Enter
Pro
ny th
ompt (chevro
F a a tine of
coe isa pr
he uset type’
code, ft
Jays the resull
©) The last lin
ready to enter
interpreter disp
(script) is written in a
te . python
preter oF script mo — rate python script 18 executed by the Pry
din the Python installation fo)
In the inter
where file name has extension “PY ~ erenasve
hon scripts are * : .
ee d again and again without retyping
interpreter. By default, 0
Once the script is created, it can be execute
Scripts are editable.
des program
To execute a script, Type the file name along with the path at the prompt.
example, if the name of the file is sum.py, WE type
>>>python sum.py
Enter 2 numbers
é y
a ?
The sum is 9
2.1.2 Python Interactive M ode
work in an inte
sommands fro!
ractive mode. It is a way of using
Python allows the user to
m the command line with
Python interpreter by executing Pytho:
script.
This, allows the user to type an expression, and immediately the expression
executed and the result is printed.
To start an interactive mode, we will see that the Python command line wind
appears as shown in Fig. 2.2.
(ec ea
BF Python 3.6 (32-bit)Data Types, Expressions, Statements =
The “>>” is the prompt used in the Python interactive mode which indicates'that
the Prompt is waiting for the Python command and produces the output
_ immediately.
example:
>>>S+7
12
>>>print(“Hello world !")
Hello world !
>>>num=10
>>>num=num/2
>>>print(num)
5.0
ee nes .
Working in the interactive mode is convenient for testing a single line code for
instant execution. But in the interactive mode, we cannot save the statements for
_ future use and we have to retype the statements to run them again.
Writing Multiline Code in Python Command Line
To write multiline code in Python interactive mode, hit Enter key for continuatior
lines, this prompts by default three dots (...). The continuation lines are needet
only in the case of procedures, branching, loop constructs. When it happens, press _
tab for indentation. _
Example:
>>>flag=1 ,
>>>if flag:
* print(“WELCOME TO PYTHON.”)
WELCOME TO PYTHON. \
>>>|
88 Problem Solving and Python Programming
2.2 DEBUGGING
A programmer can make mistakes while writing a program, and hence, the yyy
may not execute or may generate wrong output The process of identityiy,
Iso known as bugs or errors, fom a program jy ¢,"
al,
removing such mistakes,
debu;
Errors occurring in programs can be categorized as:
i) Syntax errors
ii) Logical errors
iii) Runtime errors
2.2.1 Syntax Errors
Like other programming languages, Python has its own rules that determing
syntax. The interpreter interprets the statements only if it is syntactically (as Per
rules of Python) correct. If any syntax error is present, the interpreter shows en
message(s) and stops the execution there.
Example{Parentheses must be in pairs, so the expression (20 + 22) is syntactica
correct, whereas (17 + 35 is not due to absence of right parenthesis.
Such errors need to be removed before the execution of the program) D
2.2.2 Logical Errors
A logical error is a bug in the program that causes it to behave incorrectly. A logi
error produces an undesired output but without abrupt termination of the execut
of the program. Since the program interprets successfully even when logical err
are present in it, it is sometimes difficult to identify these errors.
The only evidence to the existence of logical errors is the wrong output. WI
working backwards from the output of the program, one can identify what w
wrong.
Example: To find the average of two numbers 10 and 12 and we write the code
10 + 12/2, it would run successfully and produce the result 16. Surely, 16 is not
average of 10 and 12. The correct code to find the average should have been (1
12)/2 to give the correct output as 11.sgical errors are also called se,
Log called semantic errors as they oceur when the meaning of the
program (its semantics) is not correct
3 Runtime
runtime error causes 2 |
i. time error when apo termination of program while it is executing.
Foot execute it, Runti Ne statement is correct syntactically, but the interpreter
car . ‘ime errors do r .
as Not appea a nram starts
running oF executing, ppear until after the program start
example: In a stater i ae
Ea a ont ea wins division operation in the program, by mistake, if
the Cred is zero then it will give a runtime error like “division by
zero”.
ps'roKENS
n breaks each logical line i
Pytho h logical line into a sequence of elementary lexical components
known as tokens. A token is the smallest unit of the program, Each token
corresponds to a substring of the logical line. The tokens in Python are given in
Python
Literals Delimiter Operators
Fig. 2.3 Tokens in Python
Fig. 2.3.
f J
Keywords Identifiers
— or.
Variables
2.4 KEYWORDS
>>1.5e200 * 2.0e210
inf
iis result in the special value inf (“infinity”) rather than the arithmetically correct
sult 3.0e410, indicating that arithmetic overflow has occurred.
ithmetic underflow: Arithmetic underflow occurs when a calculated result is too
all in magnitude to be represented.
a 2p92 Problem Solving and Python Programming 1
Example:
>>>1,0¢e2300/1.0¢100 '
0.0
correct result 1002400, indie,
iy
"
This results in 0.0 rather than the arithmetically
that arithmetic underflow has occurred.
2.7.2 String Literals
String literals or strings represent a sequence of characters surrounded by quotes,
Example:
YJovita, Jesvita! "231, Carmel Nagar, 629004"
‘Hello!
A character literal is a single character surrounded by single or dojible: quotes, 7,
value with triple-quote "" is used to give multiline string literal.
Example: 0
>>>print('Welcome to Python!')
Welcome to Python!
2.8 DELIMITERS
Delimiters are symbols that perform three special roles in Python like grouping
punctuation, and assignment/ binding of objects to names. Table 2.3 presents all 24
of Python’s delimiters.
Table 2.3 Delimiters of Python
Delimiters Classification
Cfo) [ffi][t] Grouping
~t>ot:fs | @ Punctuation
= ‘= | =| %= | **= | Arithmetic assignment/ binding
= >= Bit wise assignment/ binding
ofvaturs
Values are the basic units of data, like a number or a string that a program
manipulates.gxamples: 2, 42.0 and ‘Hetlo, Wort ) -
/ - o> .,o 7 + AD
these values belong to differ, i ‘ i ii i
number, and ‘Hello, World!’ isa | aah nal
a string.
pi'ryres - Rory es
ery value belongs to i
Pata values a ae eee type in Python. Data type identifies the type
. hold and the operati
data. Data type is a category of valuce operations that can be performed on that
built in dat
The mn we 'ypes are, Numbers (Integer type, Floating Point type, and
Comp » Siting, List, Tuple, Set, Boolean and None types.
mber data types st 5 .
Nu! YP! lore numeric values, Python has three number types: integer
numbers, floating point numbers, and complex numbers.
O-9
maar taweertye CY (2) 9. $55
ieger represents
An integer type (int) represents signed whole numbers, An i
147,483,648 to
both positive and negative numbers. The range is at least
2,147,483,647. To write an int constant») c
pele oO: oO oo
¢ A zero is written as just 3 O's
e To write an integer in decimal (base 10), the first digit must not be zero.
Example:23000 —
¢ To write an integer in octal (base 8), precede it with “Oo” and use the digits
0 to 7, plus, B, @; D,B,F. — @, D —_
Example: 00177 Oroaq. Wo o
e To write an integer in hexadecimal (base 16), precede it with :0x” or “OX”.
Example: 0x77 lé Ox
e To write an integer in binary (base 2), precede it with “Ob” or “OB”.
Example: 0b101
eo Ob of
2.10.2 Floating Point Type
A floating point (float) type represents numbers with fractional part. A floating
point number has a decimal point and a fractional part.
, ae ——_——_ on
2
WTS Of, L/Problem Solving and Python Programm
tuple: 3.0 oF 3.17 oF ~28,72.
Python cannot represent very large or very small numbei
5. Phe floating point also repres
limited to only about {4-dig
I is stored with three parts.
© Asign + or— d
© A maniiss > w_*
1 in exponent 5
ands for 1.6.x10°, ie., itis the same a6 1600.0.)
Lpbxio"
le_type that holds a pair of floats, ,
Example:
2.10.3 Complex Type
The complex data type is an immutab
representing the real part and the other representing the imaginary part of a comp
number, Complex numbers are written with the real and imaginary parts joined,
++ or — sign, and with the imaginary part followed by aj
Example: de ‘
Exampl _ Atal eg 4 vf OVveP
5 +14) & ~ bs
© Python displays complex numbers in parentheses when they have a nonzero
part.
.
e Cc )
a
Example:
>>>z.imag
14.0
>>>print(z) _— /\G-o
(+14) rea:
NY >>>prim((3+3)"4+5)) Gee \)
(-7+22))
13 OS 4 4g)
cnProgram 2.1: Mustration of number type (numtype.py)
a=0b1010 #Binary Literals. oO \< _ 7
b= 100 #Decimal Literal 2 “
= 00310 #Octal Literal ~ ‘
d=0x12¢ #Hexadecimal LitesaT
#Float Type
float_l = 10.5
float_2 = 1.5e2
#Complex Type
x= 3.14) . ,
print(a, b,c, d) S+fe
print(float_1, float t_2) a
print(x, x.imiag, x.real) vO
Output:
10 100 200 300 a
10.5 150.0 = pie
3.14) 3.14 0.0 $e .
bg
2.10.4 Boolean’ Type
‘ °
A Boolean type represents special values >>Address= [‘231’, ‘Carmel Nagar’, ‘Nagercoil’, ‘629004’]
>>>print Address
[‘231’, ‘Carmel Nagar’, ‘Nagercoil’, ‘629004’]
The built-in Python function type can be used to find out’ the type of «
object.Data Type: 97
's, Expressions, Statements
Example: ay pecy
ST
>>>type(2)
>>type(“Hello”)
——
>>> 7>8
False —
3>>bool(1)
True -—
>>>bool(0)
False
p>>type((1,2,3]) -
1.10.7 Tuples C rT) C >
; ;
\ tuple is another sequence data type similar to list. A tuple consists of a sequence
f items separated by commas and items are enclosed in parenthesis ().
. SS
‘he main differences between lists and tuples are: Lists are enclosed in brackets [ ]
ad their elements and size canbe changed, while tuples are enclosed in parentheses
) and cannot be changed. .
xample:
Tuple with string values
>>>T=(‘sun','mon','tue’)
>>>print T
(‘sun', 'mon'’, 'tue')
Tuples with single character
>>>T=(PY' THON)
>>>print T
(Ps 'T'
'O'", 'N')|
are ene,
© duplic,!
cL Canny Fy
9
“ Problem Solving and Python Programming,
2.10.8 Sets
and items
Set is an unordered collection of items separated by commas
except that it cannot |
clements of a
in curly brackets { }. A set is similar to list,
entries (every clement is unique). Onee created,
changed.
J ;
{. 4
Example:
>>>x=sel("PYTHON PROGRAMMING")
>>>print(x} ~
(P', "1, Mi"Y, Th
>>>type(x)
Program2.3: Illustration of set type (settype.py)
a= {5,2,3,1,4}
# printing set variable
print(a=", a)
# data type of variable a _
print(type(a)) _
Output:
a= {1,2,3,4,5} a
2.10.9 None Type
None is a special data type with a single value. Basically, the None data type me:
nonexistent, not known or empty. It is used to signify the absence of value it
situation. None supports no special operations, and it is neither False nor 0 (zero).
Example:
>>>x=None
>>>x
>>>print x
Noneow”
Data Types, Expressions, Statements
Program 2.42 Mustration of None type (nonetype.py)
drink = "Avai'
menu(drink
menu(food)
Output:
Available ,
None
xa
In the above program, inside the menu function, if the parameter is drink then, it
displays Available. If the parameter is food, it displays None.
‘VARIABLES
A variable is an identifier, which holds a value. In programming, a value is assigned
to a variable.
Technically, a variable is the name given to the memory location to store values, so
that there is no need to remember the address of the location. Variables hold
different kind of data and the same variable might hold different values during the
execution of a program.
A variable can be used to define a name of an identifier. An identifier is a name
used to identify a variable, function, class, module or other object.
Rules for naming variables
e Variable names can be uppercase letters or lower case letters.
e Variable names can be at any length.Solving.
1g2 Proble
Hustration of arith
Prog
num = 20
num2 = 30
uum} num2 -
; Sun?
ie value of
Sum
print
Output:
The value of Sum is: 50
Here, Sum = num!
using + operator for two operands num1
nd Python Prop
tic expression (arithmetic.py)
+ num2 is an expression which does a mathematical opera,
and num2. Also, num! = 20 ,
num2 = 30, the assignment statements are called as expressions.
2. Relational/Conditional Expression
<=, etc.
This expression compares two statements using relational o
perators like >, <
Program 2.6: Illustration of Relational expression (relational.py)
nput(‘Enter first number")
a
input('Enter first number')
b
Flag = (a > b)
print ‘Is %i greater than %i: %s'% (a, b, Flag)
Output:
Enter first number 20
Enter first number 31
Is 20 greater than 31: False
Here, two values 20 and 31 are compared with a relational operator (>) and stored,
result into the variable Flag.
3. Logical Expression
The logical expression uses the logical operators like and, or, or not. The logica
expression also produces a Boolean result like either True or False.Data Types, Expressions, Statements ue
Program 2.7: Illustration of logical expression (logical.py)
a=20
b=30
23
d=21
Flag=((a > b) and (c > 4))
print "The logical expression: ((@> b) and (c > d)) returns:", Flag
Output:
The logical expression: ((a > b) and (e > d)) returns: False
Here, the logical expression combines two relational expressions with a logical
operator and i.e., the result of (a> b) is False and the result of (c > d) is True. So,
the final result is False.
4. Conditional Expression
The conditional expression is also called relational expression, This expression is
used with branching (if, if-else, etc.) and looping (while) statement. A conditional
Eerrersion alWiaiy= pradiires two msils efi True or Palee depending unan the
condition. a
Program 2.8: Illustration of conditional expression (conditional.py)
Age = input (‘Enter your age')
if (Age >= 18):
print "You can vote,"
else:
print "You can't vote."
Output:
Enter your age 25
You can vote.= Problem Solving and Python Programming
2.13 STATEMENTS
; i ter can execute. There
A Statement is an instruction that the Python ree ara encatlis each 4,
: i c
Kinds of statements: assignment (=) and print. the result. The assignme
command line, Pyth tes it and displays the ™ 7 ent
ine, Python execute + at statement is a value. (
Statement do not produce a result. The result of print s'
2.13.1 Assignment Statement
i e ‘=" symbol wi
An assignment statement associates the name to the left of th yl with y
Object denoted by the expression to the right of the ‘=" symbol.
Example:
>>>Name = ‘Jovita’
>>>Age =9
After an assignment, the values stored in the variables ‘Name and ‘Age ay
remembered.
>>>Name
‘Jovita’
>>>Age +2
i
Simultaneous Assignment Statement
Python permits any number of variables to appear on the left side, separated by
commas. The same number of expressions must then appear on the right side, again
separated by commas. |
Example:
>>>x=10
>>>y=5
>>>sum,diff,prod=x+y,x-y,x*y
>>>sum
15
>>>diffatements,
>>>prod
50
‘The expr ons are evaluated, and each
signed (o the corresponding variable.
In this case, the effect is same as the three statemen
sum =x by
diff =x-y
prod= x * y
This is termed as a ‘simultaneous
ignment statement’.
2.13.2 Print Sts
lement
The print statement takes
; : 4 series of values separated by commas. Each value is
converted into a string (by
implicitly invoking the str function) and then printed.
Example:
>>>name=input(“Enter your name: “)
Enter your name: Sugitha
>>>print(‘Hello’ name,’!”)
Hello Sugitha !
The print statement recognizes a few commands, used to format input. These are
termed ‘escape characters’, and are written as a character following a backslash.
The most common escape character is the newline character, \n. This moves the
output to a new line. The tab character, \t, moves the output to the next tab stop.
>>>print “one\n two\t three”
one
two__. three
Escape characters can also be used to embed a quote mark within a quoted
string.
>>>print ‘don\'t do that’
don’t do that106
rs or
Li numbers A
2.14 TUPLE «ite, StHlie ic lis vorn vr values 8 Para
sa finite ® ene sey
P: spined as 4 > sed
In Python, a tuple may be de ins iam ple
is similar to a list and it €°
by integers: Unlike lists, ty
etions like max() and .
commis,
Ct “ in
ie ile in vu A
sand the
The values can be of any PS and
os (). T
are enclosed within parenthe '
e.
stores values in the form of UP!
Example:
pest =(ta’, ‘b’, “0's “ds ‘e’)
>>>max(5,8,9)
9
>>>min(9,99,999)
9
Creating apis i be includ
ma is tO led at
i) To create a tuple with a single element, 4 com!
end.
>>tl = ‘a’,
Ce ates an empty tuple.
i it cre:
ii) The built-in function tuple with no argumen'
>>>t = tuple()
>>>t
0
iii) If the argument is
the elements of the sequence:
= tuple(‘Jovita’)
a sequence (string, list or tuple), the result is a tuple y
>>>t
>>>t
(0, £07, v7, *P, “a”)
Operations on tuple
The bracket operator indexes an element.
>>>t=(‘a’,e’,{7’,'0’,'w’)
>>>t[0]Data Type:
107
13]
‘eo
rhe slice OPETALOT Selects a range of elements
se :3]
cei)
‘The elements in tuples cannot be r
Modifiable, because t i able. If we
ify al . aus uples are immutable. we
0 modify one of the elements o a
wy! fthe tuple, it gives an error.
>>>t[0]='A”
Traceback (most recent call
File “”
t[O]=*A’
TypeError:
last):
> line 1, in
tuple” object does not Support item assignment
‘The elements in tuple can be replaced with one another.
>>>te(‘A’,)Ht[12]
>>at
CA’, “0°, 4, ‘0° "uy
The relational operators work with tuples and other sequences. Python starts by
comparing the first element from each sequence. If they are equal, it goes on to the
next element, and so on, until it finds the element that differs.
>>>(0, 1, 2) < 0, 3, 4)
True
>>>(0, 1, 2000000) < (0, 3, 4)
True
Program 2.9: Illustration of Tuple (tuple! .py)
T=0
print(T)
# tuple having integers
T=(1, 2, 3)
print(T)# tuple with mixed data types
T= (1. Hello", ¥4y
prin 1)
# nested tuple
T = (mouse”, (8. 4. 6), 2.)
pant)
#Indexing
MEVTUON TR: GURVALMY MENG)
pronyT]o))
prin(T]5])
# nested tuple
n_T =("mouse”, [8. 4, 6]. (1. 2, 3))
print(n_T[0][3])
print(n_T[1][1])
print(T[-1])
print(T[-6])
#Slicing
# elements 2nd to 4th
print(T[1:4])
#elements 8th to end
print(T[7:])
# elements beginning to end
print(T[:])
Output:
0
(1, 2, 3)
(1, ‘Hello’, 3.4)
(‘mouse'’, [8, 4, 6], (1, 2, 3))
P
N
s
4Datatypes 109
Xpressions, Statements
pifference between lists and tuples
«Lists are enclosed i
eae in brackets [ ] and their elements and size can be changed,
wi piss are enclosed in () and cannot be updated.
Tuples can be tho
° oan enclose the vy, oe of as read only lists, Like list, to initialize a tuple, one
‘alues in parentheses and separates them by commas.
245 TUPLE ASSIGNMENT a
ignment i i ‘
Tuple assignment is an assignment with a sequence on the right side and a tuple of
i th ight side i
variables on the left. The right side is evaluated and then its elements are assigned
to the variables on the left.
pxample:
>>>T1=(10,20,30)
>>>T2=(100,200,300,400)
>>>print Tl
(10, 20, 30)
>>>print T2
(100, 200, 300, 400)
>>>T1,T2=12,T1 # swap T1 and T2
>>>print T1
(100, 200, 300, 400)
>>>print T2
(10, 20, 30)
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.viny
Ho Proble
Example:
>>>T1=(10,20,30)
P2=( 100,200,300)
mmrts= (1006
SSSTLT291
Traceback (most recent call las):
File "", line 1, in
T1,T2=T2,T1,3
ValucError: too many values to unpack
Here, two tuples are in the left side and three tuples are in right side. So it yi,
ber of tuples in both sides to ge,
errors. Thus, it is required to have same num!
correct result.
Example:
>>>T1,T2,t3=t3,T1,T2
>>>print T1
(1000, 2000, 3000)
>>>print T2
(10, 20, 30)
>>>print t3
(100, 200, 300)
@/dpREcEDENCE OF OPERATORS (ORDER OF OPERATORS)
Evaluation of expression is based on precedence of operators. When an expressic
contains different kinds of operators, precedence determines which operator shoul
be applied first. Higher precedence operator is evaluated before the low
precedence operator.
For mathematical operators, Python follows mathematical convention. The acrony:
PEMDAS is a useful way to remember the rules:
Parentheses have the highest precedence and can be used to force a
°
expression to evaluate in the order.
Example: 5*(9 — 3) = 30
Since expressions in parentheses are evaluated first.2 Export has the next highest Precedence
x cr 1+ 283 og
Example: | 3© 9, not 27 ana
2% 3482
TR. not 36,
aoe Mt Pivision have higher precedence than Addition and
Subtraction,
Example: 2*3-1 = 5, not 4
and
6+4/2 = 8, nots,
¢ Operators with the same precedence are evaluated from left to right (except
exponentiation).
ne following Table 2.4 lists operator precedence in Python.
\
Table 2.4 Operator Precedence in Python
Operator Description
ae Exponentiation (raised to the power)
~+- Complement, unary plus and minus
*1% II Multiply, divide, modulus and floor division
+= Addition and subtraction
>> << Right and left bitwise shift
& Bitwise ‘AND’
“1
Bitwise exclusive ‘OR’ and regular ‘OR’
Comparison operators
<> == I= Equality operators
+= = %= I= *= | Assignment operators
is, is not Identity operators
in, not in Membership operators
not, or, and Logical operatorsand Python Programming
112 Problem
2.17 COM
* A comment statement contains information for persons reading the py,
1,
Comments make the program casily r ible and understandab|e by
'
programmer and non-programmer who are secing the code.
e Comment statements are non-exccutable statements so they are itn
during program execution.
° In Python, a comment starts with # (hash sign). Everything following 4,
Ul the end of that line is treated as a comment and the interpreter Sinn
ignores it while executing the statement. They have no effect on the Pros
results,
Example:
l# swap.py )
# Swapping the values of a two variable program
# written by G. Sugitha, April 2018
2.18 MUTABLE AND IMMUTABLE TYPES
Sometimes we may require changing or updating the values of certain Variabh
used in a program. However, for certain data types, Python does not allow Us |
change the values, once a variable of that type has been created and assigned valu
Python data types can be classified into two types. They are,
1. Mutable type or
2. Immutable type.
Mutable (changeable) type
Variables whose values can be changed after they are created and assigned ar
called mutable or an object whose state or value can be changed in place is said t
be mutable type. Lists and Dictionaries are mutable, that means user ca
del/add/edit any value inside the lists and dictionaries.
Immutable (unchangeable) type
Variables whose values cannot be changed after they are created and assigned ax
called immutable or an object whose state or value cannot be changed in place issaid to be ble type. When an attempt is made to update the value of an
immutable variable, the old value is destroyed and a new variable is created by the
same name in memory, Integers, Float, Boolean, Complex, Strings, T ‘uples and »
¢ immutable data types,
ar
2.19 INDENTATION
whitespace et the beginning of the line is called indentation. These whitespaces or
the indentation are very important in Python.
whitespace including Spaces and tabs at the begi
the indentation level of that logical line.
In a Python program, the leading
inning of the logical line determines
The are a paoeration Sroups statements to form a block of statements. This
means tha ‘ a ae in a block must have the same indentation level. Python ve
‘Dstrictly checks the indentation level and gives an error if indentation is not correct.
Program 2.13: Illustration of indentation (voting.py)
oO age = int(input("Enter ag
if (age>18):
print(Eligible for voting’)
))
else:
print(‘Not Eligible for voting’)
Like other programming languages, Python does not use curly braces ({ .. .} ) to
indicate blocks of code. It uses only indentation to form a block. All statements
inside a block should be at the same indentation level.
2.20 INPUT FUNCTION
2.20.1 inputQ Function
The purpose of input() function is to read input from the standard input (the
keyboard, by default). Using this function, we can extract integer or numeric values.
Syntax:
= input([prompt})Python Programming 1
solving and
tg
Here,
© The prompt is an optional parameter.
© = The prompt is an expr on that serves to prompt the user for inpy, 1
almost always a string literal which is enclosed within quotes (yj, \
double) with parentheses.
© The result of input() function is returned a numeric value, and assip,,
variable. I
© When the input() function executes, it evaluates the prompt and display
result of the prompt on the screen. .
Example:
>>>num1 = input("Enter first number:
Enter first number: 20
>>>num2 = input("Enter second number:
Enter second number: 40
>>>print "Sum is:", num1+num2
Sum is: 60
2.20.2 raw_input0
The purpose of raw_input() function is to read input from the standard input stre,
(the keyboard, by default). Using this function, we can extract string of charact
(both alphanumeric and special).
Syntax:
= raw_input([‘prompt'])
Here,
the user) and returns a string
This function reads a line from input
stripping a trailing newline.
It always returns a string.Data es, E:
ata Types, Expressions, statements ms
example:
Name = raw_input("Enter name:")
Address = raw_input(‘Enter addre:
act an integer value usi: F .
To get ae Sg raw_input() function, you have to convert the input
string int into respective data types using int(), float(), etc.
program 2.10: Illustration of raw input function
Num1 = int(raw_input("Enter fist number")
nee int(raw_input("Enter second number:"))
print 'The sum of, Num1,' and’, Num2, is, Num1+Num2
Output:
Enter first number: 24
Enter second number: 67
The sum of 24 and 67 is 91
ILLUSTRATIVE PROGRAMS
1. Exchange the values of two variables
|
def exchange(x,y): #Function Definition
XYHYX # swapping using tuple assignment
print(""After exchange of x,y")
print("x =",x)
print("Y= ",y)
x=input("Enter value of X") #Main Function
y=input("Enter value of Y ")
print("Before exchange of x,y")
print("x =",x)
print("Y= ",y)
exchange(x,y) # Function callni0) Problem Solving and Python Programming
Exchange the values of two variables using temporary variables
input(‘Enter value of
ut(’Enter value of Y:
c hange of xy")
x
print(""After exchange of x,y")
print("x =",x)
print("Y="\y)
Output:
Enter value of X: 67
Enter value of Y: 56
Before exchange of x,y
7
Y= 56
After exchange of x,y
x=56
Y= 67
2. Circulate the values of n variables without using slicing technique.
def circulate(A,N):
for i in range(1,N+1):
B=A.pop(0)
A.append(B)
print("Circulation ",i,"="
return
A=[91,92,93,94,95]
N=int(input("Enter n:"))
circulate(A,N)[[circulate the values of
[cireulal u¢s of'n variables using slicing technique
def cireulate(A.N):
for i in range(I,N+1);
B=A[i:}+A[:i]
print("Circulation ",
return
A=[91,92,93,94,95]
N=int(input("Enter n:"))
circulate(A,N)
Output:
Enter n:5
Cireulation 1 = [92, 93, 94, 95, 91]
Circulation 93, 94, 95, 91, 92]
Circulation 94, 95, 91, 92, 93]
Circulation 4 =[95, 91, 92, 93, 94) LT
Circulation 5 =[91, 92, 93, 94, 95]
—
N
w
3. Finding distance between two points ()
import math
= int(input("Enter a x1: "))
int(input("Enter a y1: "))
int(input("Enter a x2: "))
int(input("Enter a y2: "))
yi
x!
¥
distance = math.sqrt(((x2-x1)**2)+((y2-y1)**2))
print(""Distance = ",distance)
Output:
Enter a x1: 3
Enter a yl: 2
Enter a x2: 7
Enter a y:
Distance = 7.2111025509279786
Data Types, Expressions, Statements
[[Girentate the values of n variables using slicing technique
ef eireulate(A.N):
for i in range(1,N+1):
B=A[i:}+AL:i]
print("Circulation "i
return
AA(91,92,93,94,95]
N=int(input("Enter n:"))
circulate(A,N)
‘Output:
Enter n:5
Circulation 1 = [92, 93, 94,95, 91]
Circulation 2 =[93, 94, 95, 91, 92]
Circulation 3 =[94, 95, 91, 92, 93}
Circulation 4=[95,91,92,93, 94) __
Circulation 5=[91, 92, 93, 94, 95]
=
|: Finding distance between bvo points) GD
a
import math
x1 = int(input("Enter a x
int(input("Enter a y
= int(input("Enter a x2: "))
y2 = int(input("Enter a y2: "))
distance = math.sqrt(((x2-x1)**2)+((y2-y1)**2))
print("Distance = ",distance)
Output:
Enter a x1:3
Enter a yl: 2
inter a x2: 7
fer a y2: 8
Distance = 7.211102550927978yy and Python Programming
Problem Solviny
PUTATIONAL PROGRAMS
118
1 SIMPLE COM
1, Average of three numbers
mum
num2 = int(input("Enter a number
num3 = int(input("Enter a number: "))
sum = num|+num2+num3
avg=sun/3
print(‘The average of {0}, {1} and {2} is {3}'.format (num1, num2,num3,avg))
Output:
Enter a number: 67
Enter a number: 34
Enter a number: 84
The average of 67, 34 and 84 is 61.666666666666664
2. Area of circle
PI=3.14
r= float(input("Enter Radius: "))
area=PI*r*r
print(The area = ', area) .
Output:
Enter Radius: 2
The area = 12.56
3. Area of square
a = int(input("Enter a side: "))
area= a*a
print('The area = ', area)
Output:
Enter a side: 4
The area = 16A Arca of triangle whoye ties arene
a= Hoar input(Enter first side: yy
y= Hloattinput(’Bater second side: yy
Aoat input’ Enter thid side: 9)
qatbeey/2
(s*(s-ay*(s—by
©
Rca se) ** 0,5
prin The area of the triangle is 90.26" Saareny
Output:
Enter first side: 4
Enter second side: 4
Enter third siele: 7
The area of the triangle is 6.78
5. Finding surface area and volume of sphere
radius = float(input(‘Enter the Radius of'a Sphere: ))
= 4*PI*radius*radius
Volume = (4/3)*PI*radius*radius*radius
print("\n The Surface area of a Sphere = %.26" Ysa)
print("\n The Volume of a Sphere = %.2P" %Volume)
Output:
Enter the Radius of a Sphere: 4
The Surface area of a Sphere = 200.96
The Volume of a Sphere = 267.95
6. Converting Centigrade to Fahrenheit 2
C= float(input("Enter celsius: "))
F=(C* 1.8) +32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit’ %(C,F))
Output:
Enter celsius: 30
30.0 degree Celsius is equal to 86.0 degree Fahrenheitproblem Solvay
7, Converting Fahrenhelt (0
F = Moatinput(" Enter Fahrenheit: ")) 7
=F -32)* 619) ago. urdegree Colsis (PC)
0.1 degree Fahrenheit js equal 10 %0-
print(%
‘Output
Fahrenheit: 45 gree Celsius
E
45.0 degree Fahrenhe'
%. Calculating simple interest
nt: ")
P= int(input("Enter Principal Amou!
t(input("Enter rate of interest: "))
N= int(input("Enter number of years * ")
si=(N*P*R)/100
print(' Simple Interest “.si)
it is equal to 7.2 de!
Output:
Enter Principal Amount: 101
Enter rate of interest: 7
Enter number of years : 10
Simple Interest : 7000.0
000
9. Calculating compound interest
int(input("Enter Principal Amount: ")
int(input("Enter rate of interest: "))
int(input("Enter number of years :"))
t(input("Enter time : ")
ci=P*(1+R/N)*N*t
print(' Compound Interest :',ci)
Output:
Enter Principal Amount: 10000
Enter rate of interest: 8
Enter number of years : 15
Enter time : 10
Compound Interest : 2299999.9999999995Data Types, Expressions, Statens =
= temp
rint(‘The value of x after swapping: 'x)
print(The value of y after swapping: "y)
‘Output:
gnter value of x: 34
Enter value of y: 67
The value of x after swapping: 67The value of y after swapping: 34
11. Swapping two numbers without using temporary variable
pl = int(input(‘Enter value of nl: ) Q
n2= int(input(Enter value of n2: '))
n2=nl+n2
nl=n2-nl
n2=n2-nl
print("The value of nl after swappin, ‘nl)
print(‘The value of n2 after swapping: 'n2)
Output:
Enter value of nl: 78
Enter value of n2: 34
The value of nl after swapping: 34
The value of n2 after swapping: 78
12. Computing the distance between the points (x1, y1) and (x2, y2) @)
import math
x1 = int(input("Enter a number: "))
yl = int(input("Enter a number:
x2 = int(input("Enter a number:
y2 = int(input("Enter a number: "))
pl=[xl, yl]
p2 = [x2, y2]
distance = math.sqrt( ((p1[0]—p2[0])**2)+((p1[1]-p2[1])**2) )
print(distance)Problem Solving and Python Pr
Outpag
Enter a number: 4
F
i
13. Finding square root of a number
num= inpul("Enter a number: ")
number = float(num)
squareroot = number ** 0.5
print("Square Root of %0.2f is %0.2f" %(number, squareroot))
Output:
Enter a number: 10
Square Root of 10.00 is 3.16
14. Exponentiation of a number
import math
num = int(input("Enter a number: "))
ex=math.exp(num)
print (‘Exponentiation =',ex)
Output:
Enter a number: 50
Exponentiation = 5.184705528587072c+21
15. If I leave my house at 6:52 am and run 1 mile at an easy pace
permile), then 3 miles at tempo (7:12 per mile) and 1 mile at eas:
again, what time do I get home for breakfast?
start = (6*60+52)*60
easy = (8*60+15)*2
fast = (7*60+12)*3
finish_hour = (start + easy + fast)/(60*60.0)
finish_floored = (start + easy + fast)//(60*60)
finish_minute = (finish_hour - finish_floored)*60
print(‘Finish time was %d:%d',finish_hour,finish_minute)re
Data Types,
Pes, Expressions, Statements a
time WAS 7.501666066066067
ri jgo0n000000016
FA Simple calculator
Sarl 9)!
return x +Y
gubtract(x, y):
return X~ ¥
get multiply, yy
return x * y
got divides y=
return x/ ¥
def
Select operation,")
1.Add")
jnt("2.Subtract")
ue prea Multiply")
print" Divide")
choice = input("Enter choice( 1/2/3/4):")
num! = intGnput("Enter first number: "))
num2 = int(input("Enter second number: "))
ifchoice = '1':
print(num1,"+",num2,"=", add(num! num2))
elif choice = '2':
print(num1,"—";num2,"="
elif choice ==
print(num1,"*",num2,"
elif choice
print(num!
rint(’
re 7
» Subtract(numlnum2))
, multiply(numl num2))
, divide(numt num2))
else:
print("Invalid input")
Output:
Select operation.
1. Add
2. Subtract
3. Multiply
4. Dividecr Vay
first number: 48
second number: 7
$2
ANNA UNIVERSITY 2 MARK QUE
ANSWERS
PIONS WITH —
' , rogram? °
1, Are comments executable statements in a Python program? How COMM,
My
\
are included in a python program?
Refer Page No.: 112
(AU Nov/Dec 2021, 1249!
f
2. Identify the operand (s) and operator (s) in the following expression:
sum=a+b.
sum, a, b are operands
=, + are the operators
(AU Nov/Dec 2021, Raqp,
}
3. Compare interpreter and compiler. What type of Translator is used fo,
Python?
Python uses interpreter as a translator.
(AU Nov/Dec 2019, R291,
whole program at one go.
oe Compiler Interpreter
no
1, | The compiler takes a program as a Interpreter translates a program
“| whole and translates it. statement by statement.
9, | intermediate code or target code is Interpreter doesn’t create intermediate
“| generated in case of a compiler. code.
A compiler is comparatively faster than . .
E parauyey Interpreters compile each line of code
3. | Interpreter as the compiler take the
after the other.
In compiler when an error occurs in the
program, it stops its translation and
after removing error whole program is
translated again
When an error takes place in the
interpreter, it prevents its translation
and after removing the error,
translation resumes.Data Ty
Pes, Expressions, Statements
in a compiler, the process requl
steps in which firstly source nN?
translated to target code
executed .
is
Program then
which Sot
executed at the sa
The compiler is used in
languages like C, Cur, cy eoeramming | Tnterprete
» Scala, ete. | like PHP, Ruby, Python, etc.
t K ? Gi
GP nat are Keywords? Give Examples. (AU Dee/San 2019, R2017)
Keywords are reserved words that
cannot be used as ordina have predefined meanings in python. They
ry identifie:
Siten python3 has 33 keyworg sie" 80d must be spelled exactly as they are
Keywords of Python
False class finally is return
None continue | for lambda try al
awe act from nonlocal _| while
global not with
as elif if or yield
assort else import pass
break except in Taise
5, State the reasons to divide Programs into functions.
(AU Dec/Jan 2019, R2017)
e The length of the source program can be reduced by dividing it into smaller
functions.
e By using functions it is very easy to locate and debug an error.
e The user-defined function can be used in many other source programs
whenever necessary.
e Functions avoid coding of repeated programming of the similar instructions.
4, Name the four types of scalar objects Python has. (AU Jan 2018, R2017)
The commonly used scalar types in Python are:
Integers (type int), floating point numbers (type float), strings (type str),
Booleans (type bool) and lists are a set of scalar objects in Python.Problem Solving and Python Programming
126
example,
ENWhat is 0 Tuple? How literals of type tuple are written? Give
(AU Jan 2018, Ray),
A tuple may be defined as a finite, atic list of numbers or string. It Conta,
immutable sequence of values separated by commas, The values can be of y,
type, and they are indexed by integers. Literals of type tuple are enclosed wiy,
parentheses ().
Example:
Sp t= (‘a’, ‘b’, ‘c’, ‘a’, ‘e’)
>>>max(5,8,9)
9
G2What is interpreter mode in Python?
The interpreter mode is the mode where
run in the Python interpreter.
QWnat is interactive mode in Python?
The interactive mode is a command line shell which gives immediate feedba
for each statement, fed statements in active memory. As new lines are fed in
the scripted and finished .py files
the interpreter, the fed program is evaluated both in part and in whole.
8. Name five primitive data types in Python.
Five primitive data types in Python are: Numbers, String, List, Tuple a
Dictionary.
). What does ‘immutable’ mean; which data type in python are immutable?
An object whose state or value cannot be changed in place is said to
immutable type. So, a sequence that is immutable sequence is one that canr
change. For example, Strings and Tuples are immutable.
10. What are escape sequences? Write any four escape sequence in Python.
Escape sequences are non printable characters. It consists of backslash follow
by a character both are enclosed within single quotes.i Se
Data Types,
2 ‘Types, Expressions, Statements =
Backslash(\)
< Single quote(*)
" Double quote(")
\o ASCII Bell (BEL)
1s, Define Value.
A value is the basic units of data, like a number or a string that a program
manipulates.
1p, What are the types used in Python?
Types is a category of values. Integers (type int), floating point numbers (type
float), strings (type str), Booleans (type bool) and lists are a set of predefined
data types in python. They are called as built-in-types.
13. What is boolean type in Python?
A Boolean type represents special values True and False. The most common
way to produce a Boolean value is with a relational operator
14, How can you create a complex literal in Python?
Complex literals can be created by using the notation x + yj where x is the real
component and y is the imaginary component. For example, >>> 1j * 1j which
produces the result as: (-1+0j).
15. What is a variable?
A variable is an identifier, which holds a value. In programming, we assign a
value to a variable. Technically, a variable is a reference to a computer
memory, where the value is stored.
6. List out the rules to be followed in naming variable.
e Variable names can be at any length.
e They can contain both letters and numbers, but they can’t begin with <
number.
e Both uppercase letters and lower case letters can be used.and Python Programming,
Problem Solving
ame. It is often used in na,
“he
128
© The underscore (_) character can appear in a.nd
with multiple words.
© A variable name cannot be any one of the keywords.
nkei .
aAwn t is expression?
ables, and operators. A value,
‘An expression is a combination of values, vari
pression. Expressions, most commonly, consist of
itself is considered as an ex)
combination of operators and operands.
Example: 5 + (8 * k)
us assignment statements.
18. Give example for simultaneo'
Simultaneous Assignment Statement
Python permits any number of variables to appear on the left side separated |
ber of expressions must then appear on the right sig
commas. The same num!
again separated by commas.
Example:
>>>x=10
>>>y=5
>>>sum, diff,prod=xty,x—y,x
>>>sum
15
>>>diff
5
>>>pr
50
{o)-What is a tuple? Give example.
A tuple is a immutable sequence of values. They are comma separated list
values. The value can be any type, and they are indexed by integer.
Example:
S>>t = ‘a’, ‘b’, ‘c’, ‘a’, fe”
>>ot=(‘a', "bY, ‘0’, @’,‘e’)ee EEE?
Dat
a Types, 9
pe Types, Expressions, Statements $29
create a tuple?
a tuple:
ea tuple with a single et 7
Pe with a single clement, final comma is to be included
>a =
a er wa: create i ,
ii) Another way to create a tuple is the built-in function tuple. With no
argument, it creates empty tuple:
>>>t = tuple()
>>>1
0
iii) If the argument is a sequence (string, list or tuple), the result is a tuple with
the elements of the sequence:
>>>t= tuple(‘Jovita’)
>>Dt
CPs ow, “0, a’)
21, How can we declare variables in Python?
Python variables do not have to be explicitly declared to reserve memory space.
The declaration happens automatically when you assign a value to a variable.
The equal sign (=) is used to assign values to variables.
12, How bracket operator used in tuple?
The bracket operator indexes an element.
>>>t=(‘a’,‘e’,i’,‘0’,w’)
>>>t[0]
a
>>>t[3]
0
The slice operator selects a range of elements.
>>>1[1:3]
Ce’, i’)on Problem Solving and Python Programming,
23. Give the precedence of operators in py
precedence and can be used t0 fore
Parentheses have the highest
°
expression to evaluate in the order.
Example: 5*(9 — 3) = 30 since expressions in parentheses are CV alate
first.
Exponentiation has the next highest precedence.
Example: | + 2**3 = 9, not 27 and
2 * 3**2 = 18, not 36.
¢ Multiplication and Division have higher precedence than Addition an
Subtraction.
Example: 2*3—1 = 5, not 4 and
6+4/2 = 8, not 5
ANNA UNIVERSITY 16 MARK QUESTIONS WITH
ANSWERS
1. Outline the data types supported by Python with an example.
(AU Nov/Dec 2021, R202)
Refer Page No.:93
2. Name the types of operators supported by Python and outline any two wit
an example. (AU Nov/Dec 2021, R2021
Refer Page No.:137
3. Write a python program to rotate a list by right n times with and witho.
slicing technique. (444
(AU Nov/Dec 2019, R2013
Refer Page No.:116
4, Discuss about keyword arguments and default arguments in python wit
(444
example.
(AU Nov/Dec 2019, R2017
Refer Page No.:170,172uate the follo
thon,
ing expr
NE expressions in py
i. 24/6%3
ii, float(4+ini(2, 390,
iii, 2regeng OP)
(6)
(AU Nov/Dec 2019, R2017)
answer?
D 24/6%3
=4%3
ii) float (4 + int (2.39 a
a %
=float( 4 + 2% 2) az)
=float ( 4)
=4.0
iii) 2**2**3
=2 ** (4%
(2**3) 4 Pea Precedence of exponentiation (**) is Right to
=2**g -
= 256
Bicich We structures of interpreter and complier. Detail the differences between
them. Explain how python works in interactive mode and script mode with
examples. (8)
(AU Dee/Jan 2019, R2017)
Interpreters and compilers are very similar in structure, The main difference is
that an interpreter directly executes the instructions in the source programming
language while a compiler translates those instructions into efficient machine
code.
Compiler:
4 compiler takes entire program and converts it into object code which is
ypically stored in a file. The object code is also refereed as binary code and
an be directly executed by the machine after linking. Examples of compiled
rogramming languages are C and C++.nz problem Solving and Python Pré
Fron
Interpret a ?
An Interpreter dircetly executes instructions written in @ PYORMMM|
scripting, language without previously converting, them £0 an ODjECL Coq, |
veal Hanguages are Perl, Python and May,
machine code. Examples of interp!
ad intery
compiler
rences betwe
Comp
The compiler takes a program as @
it
whole and translat
Intermediate code or target code is
generated in case of a compiler.
(er
Interpreter
translates prop,
Interpreter
statement by statement.
Interpreter doesn’t create intermeg
code.
A compiler is comparatively faster
take
than Interpreter as the compiler
the whole program at one go.
Interpreters compile each line of ¢
after the other.
When an error takes place in |
Tn compiler when an error occurs in
4__| the program, it stops its translation and
~ | after removing error whole program is
translated again
interpreter, it prevents its translat)
and after removing the en
translation resumes.
Ina compiler, the process requires two
steps in which firstly source code is
translated to target program then
executed
The compiler is used in programming
languages like C, C++, C#, Scala, etc.
Interpreter is a one step process
which Source code is compiled
executed at the same time.
Interpreter is employed in langua,
like PHP, Ruby, Python, etc.
Python Interpreter mode or Script mode:
In the interpreter or script mode, a Python program (script) is written in a f
where file name has extension “.py”. The Python script is executed by
Python interpreter. By default, the Python scripts are saved in the Pytl
installation folder. Once the script is created, it can be executed again and ag
without retyping. The Scripts are editable.foe file name
t. Por
a > prompt
example. Me OF the file ig
along with the path at the
SUM. Dy, we type
Pythen sum.py
will give the output as, —
>>>python sum.py
Enter 2 numbers
6
3
The sum is 9
python Interactive Mode:
yf = as
script. This allows the user ‘0 type an expression, and immediately the expression is
executed and the result is printed,
gxample:
>>>st+7
12
>>>print(“Hello world !”)
Hello world !
5, What is a numeric literal? Give examples. (4)
(AU Jan 2018, R2017)
Refer Page No.: 91
6. Appraise the arithmetic operators in Python with an example.
(12)
(AU Jan 2018, R2017)
Refer Page No.: 137
7. Outline the operator precedence of arithmetic operators in Python. ©)
(AU Jan 2018, R2017
Refer Page No.:110oy
ase) Problem Solving and Python Programming
8. Write a Python Program to exchange the value of bo variables.
Ss (AU Jan 2018. Ril!
* RH)
Refer Page No.:
1
a
9. Explain the following with suitable example.
i) Tuple assignment.
ii) Precedence of operators.
Refer Page No.: 109 & 110
10. Write a Python program to test for leap year.
Program:
year = int(input("Enter a year: "))
if (year % 4) =
if (year % 100) = 0:
if (year % 400) = 0:
print("{0} is a leap year".format(year))
else:
print("'{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
Output:
Enter a year: 2000
2000 is a leap year