Unit 2 - DATA, EXPRESSIONS, STATEMENTS
Unit 2 - DATA, EXPRESSIONS, STATEMENTS
STATEMENTS
UNIT 2
UNIT 2
Python interpreter and interactive mode, debugging; values and types: int, float,
boolean, string , and list; variables, expressions, statements, tuple assignment,
precedence of operators, comments; Illustrative programs: exchange the values
of two variables, circulate the values of n variables, distance between two points.
PYTHON INTERPRETER AND INTERACTIVE MODE
Python 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 both in part and in whole .
The Python interpreter is a program that reads and executes Python code, in which Python
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 environment, start the interpreter by clicking on an icon, or by typing
python on a command line.
Traditionally, python programs are stored in a file with the
The first three lines contain information
about the interpreter and the operating extension .py . Consider the file sum.py. Once the file is
system it is running on. created, start the python system and give the file name on the
command line, as follows:
The version number is 3.6.0. It begins with 3,
i) Syntax errors
Example: Parentheses must be in pairs, so the expression (20 + 22) is syntactically correct,
whereas (17 + 35 is not due to absence of right parenthesis.
The only evidence to the existence of logical errors is the wrong output. While working backwards from the output of
the program, one can identify what went wrong.
Example: To find the average of two numbers 10 and 12 and we write the code as 10 + 12/2, it would run
successfully and produce the result 16. Surely, 16 is not the average of 10 and 12. The correct code to find the average
should have been (10 + 12)/2 to give the correct output as 11.
Logical errors are also called semantic errors as they occur when the meaning of the program (its
semantics) is not correct.
Runtime Error
A runtime error causes abnormal termination of program while it is executing. Runtime error is
when the statement is correct syntactically, but the interpreter cannot execute it. Runtime errors
do not appear until after the program starts running or executing.
Python Tokens
Arithmetic overflow: Arithmetic overflow occurs when a calculated result is too large in
magnitude to be represented.
Example:
>>>1.5e200 * 2.0e210
inf
This result in the special value inf (“infinity”) rather than the arithmetically correct result 3.0e410,
indicating that arithmetic overflow has occurred.
Arithmetic underflow: Arithmetic underflow occurs when a calculated result is too small in
magnitude to be represented.
Example:
>>>1.0e2300/1.0e100
0.0
This results in 0.0 rather than the arithmetically correct result 1.0e2400, indicating that
arithmetic underflow has occurred.
String Literals
String literals or strings represent a sequence of characters.
Example:
'Hello' 'Jovita, Jesvita' "231, Carmel Nagar, 629004"
In Python, string literals may be delimited (surrounded) by a matching pair of either single (') or
double (") quotes.
Example:
>>>print('Welcome to Python!')
Welcome to Python!
DELIMITERS
Delimiters are symbols that perform three special roles in Python like grouping, punctuation,
and assignment/ binding of objects to names. Table presents all 24 of Python’s delimiters.
Delimiters of Python
Delimiters Classification
( ) [ ] { } Grouping
. , : ; @ Punctuation
print("b:", b)
None Type
None is a special data type. Basically, the None data type means nonexistent, not known or
empty. This is a unique value that may be used where it is required but there is no obvious
value. This value has its own type and is the only instance of that type.
Example:
>>>x=None
>>>x
>>>print x
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.
Declaring Variables
Variables are declared according to the Python character sets. A variable is declared to hold some value.
Variables are examples of identifiers.
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.
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.
Example:
Roll_no, GrossPay, a1, salary
Creating Variables
The assignment statement (=) assigns a value to a variable. The usual
assignment operator is =.
Syntax:
Here variable is an identifier and ‘expr’ is an expression. The meaning of
the assignment is that, the expression on the right side is evaluated to
produce a value, which is then associated with the variable named on the
left side.
variable = expr
Example:
◦>>>n=10
>>>name=“Jovita”
>>>PI=3.14
>>>7wonders=‘tajmahal’
SyntaxError: invalid syntax // It is illegal because it begins with a number.
>>>student_name=‘Denisha’
>>>a=b=c=d=10
>>>(a,b,c,d)
(10,10,10,10)
EXPRESSIONS
In Python, most of the lines or statements are written in the form of expressions. Expressions
are made up of operators and operands. Expressions are evaluated according to operators.
An expression is a combination of values, variables, and operators. Expressions combine
variables and constants to produce new values. A value by itself is considered an expression.
Expressions, most commonly, consist of a combination of operators and operands. Operand is
the value on which operator is applied. These operators use constants and variables to form an
expression.
Example:
A * B + C
Where *, + are operators; A, B and C are operands.
Types of expressions
Based on the position of operators in an expression
Based on the position of operators in an expression, Python supports three types of expressions. They are,
Infix expression: The operator is placed in between the operands.
Example: a=b+c
Prefix expression: The operator is placed before the operands.
Example: a=+bc
Postfix expression: The operator is placed after the operands.
Example: a=bc+
Based on the type of the result obtained on
evaluating an expression
Based on the type of the result obtained on evaluating an expression, Python supports four types of expressions.
Arithmetic Expression
This type of expression just do mathematical operations like +, –, *, / etc.
Illustration of arithmetic expression (arithmetic.py)
num1 = 20
num2 = 30
Sum = num1 + num
print 'The value of Sum is:', Sum
Output:
The value of Sum is: 50
Here, Sum = num1 + num2 is an expression which does a mathematical operation using + operator for two operands num1
and num2. Also, num1 = 20 and num2 = 30, the assignment statements are called as expressions.
Relational/Conditional Expression
This expression compares two statements using relational operators like >, <, >=, <=, etc.
Illustration of Relational expression (relational.py)
a = input('Enter first number')
b = input('Enter first number')
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 a result into the variable Flag.
Logical Expression
The logical expression uses the logical operators like and, or, or not. The logical expression also produces a Boolean result
like either True or False.
Illustration of logical expression (logical.py)
a = 20
b = 30
c = 23
d = 21
Flag=((a > b) and (c > d))
print "The logical expression: ((a > b) and (c > d)) returns:", Flag
Output:
The logical expression: ((a > b) and (c > 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.
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 expression always produces two results either True
or False depending upon the condition.
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.
STATEMENTS
A statement is an instruction that the Python interpreter can execute. There are two kinds of
statements: assignment (=) and print.
When a statement is typed in the command line, Python executes it and displays the result.
The assignment (=) statement do not produce a result. The result of print statement is a value.
Assignment Statement
An assignment statement associates the name to the left of the ‘=’ symbol with the 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’ are remembered.
>>>Name
‘Jovita’
>>>Age + 2
11
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,xy,x*y
>>>sum
15
>>>diff
5
>>>prod
50
The expressions are evaluated, and each is assigned to the corresponding variable. In this case,
the effect is same as the three statements:
sum = x + y
diff = x – y
prod= x * y
This is termed as a ‘simultaneous assignment statement’.
Print Statement
The print statement takes a 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 that
TUPLE
In Python, a tuple may be defined as a finite, static list of numbers or string. A tuple is similar to a list and it contains
immutable sequence of values separated by commas.
The values can be of any type, and they are indexed by integers. Unlike lists, tuples are enclosed within parentheses
( ). The built-in functions like max() and min() stores values in the form of tuple.
Example:
>>>t = (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
>>>max(5,8,9)
9
>>>min(9,99,999)
9
Creating a tuple
To create a tuple with a single element, finally comma is to be included.
>>>t1 = ‘a’,
Another way to create a tuple is the built-in function tuple with no argument that creates an empty tuple.
>>>t = tuple()
>>>t
()
If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of the sequence:
>>>t = tuple(‘Jovita’)
>>>t
(‘J’, ‘o’, ‘v’,’i’, ‘t’, ‘a’)
Operations on tuple
The bracket operator indexes an element.
>>>t=(‘a’,‘e’,‘i’,‘o’,‘u’)
>>>t[0]
‘a’
>>>t[3]
‘o’
The slice operator selects a range of elements.
>>>t[1:3]
(‘e’, ‘i’)
The elements in tuples cannot be modifiable, because tuples are immutable. If we try to modify one of the elements of the
tuple, it gives an error.
>>>t[0]=‘A’
Traceback (most recent call last):
File “<pyshell#6>”, line 1, in <module>
t[0]=‘A’
TypeError: ‘tuple’ object does not support item assignment
The elements in tuple can be replaced with one another.
>>>t=(‘A’,)+t[1:]
>>>t
(‘A’, ‘e’, ‘i’, ‘o’,‘u’)
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. Subsequent elements are not considered (even if they are
really big).
>>>(0, 1, 2) < (0, 3, 4)
True
>>>(0, 1, 2000000) < (0, 3, 4)
True
Difference between lists and tuples
Lists are enclosed in brackets [ ] and their elements and size can be changed, while tuples are
enclosed in ( ) and cannot be updated.
Tuples can be thought of as read only lists. Like list, to initialize a tuple, one can enclose the
values in parentheses and separates them by commas.
TUPLE ASSIGNMENT
Tuple assignment is an assignment with a sequence on the right side and a tuple of variables on
the left. The right side is evaluated and then its elements are assigned to the variables on the
left.
Example:
>>>T1=(10,20,30)
>>>T2=(100,200,300,400)
>>>print T1
(10, 20, 30)
>>>print T2
(100, 200, 300, 400)
>>>T1,T2=T2,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.
Example:
>>>T1=(10,20,30)
>>>T2=(100,200,300)
>>>t3=(1000,2000,3000)
>>>T1,T2=T2,T1,t3
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
T1,T2=T2,T1,t3
ValueError: too many values to unpack
Here, two tuples are in the left side and three tuples are in right side. So it gives errors.
Thus, it is required to have same number of tuples in both sides to get the correct result.
Example:
>>>T1,T2,t3=t3,T1,T2
>>>print T1
(1000, 2000, 3000)
>>>print T2
(10, 20, 30)
>>>print t3
(100, 200, 300)
PRECEDENCE OF OPERATORS (ORDER
OF OPERATORS)
When an expression contains more than one operator, the order of evaluation depends on the
order of operations.
For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is
a useful way to remember the rules:
Parentheses have the highest precedence and can be used to force an expression to evaluate in
the order.
Example: 5*(9 − 3) = 30
Since expressions in parentheses are evaluated first.
PEMDAS
Exponentiation has the next highest precedence.
Example: 1 + 2 ** 3 = 9, not 27 and
2 * 3 ** 2 = 18, not 36.
Multiplication and Division have higher precedence than Addition and Subtraction.
Example: 2 * 3 1 = 5, not 4 and
6 + 4 / 2 = 8, not 5.
Operators with the same precedence are evaluated from left to right (except exponentiation).
Operator Precedence in Python
COMMENTS
A comment statement contains information for persons reading the program.
Comments make the program easily readable and understandable by the programmer and non-
programmer who are seeing the code.
Comment statements non-executable statements so they are ignored during program execution.
They have no effect on the program results.
The program lines begin with the hash sign, #.
In Python, this symbol is used to denote a comment statement.
Example:
# swap.py
# Swapping the values of a two variable program
# written by G. Sugitha, April 2018
FLOW OF EXECUTION
The order in which statements are executed during a program run is called flow of execution. A
function should be defined before its first use.
Consider the program
n1 = input("Enter first number:")
n2 = input("Enter first number:")
Sum = n1 + n2
print "Sum of %d and %d is: %d"% (n1, n2, Sum)
From the above four lines, the flow of execution will start from line 1 till line 4. If there are any
branching or looping statements used in a program, then the flow of execution may depend on
the condition.
MUTABLE AND IMMUTABLE TYPES
In Python, the data objects hold values in two forms. They are,
1. Mutable type or
2. Immutable type.
Mutable (changeable) type
An object whose state or value can be changed in place is said to be mutable type. Lists and
Dictionaries are mutable, that means user can del/add/edit any value inside the string and tuple.
Immutable (unchangeable) type
An object whose state or value cannot be changed in place is said to be immutable type. Strings
and Tuples are immutable, that means user cannot del/add/edit any value inside the string and
tuple.
INDENTATION
Whitespace at the beginning of the line is called indentation. These whitespaces or the
indentation are very important in Python.
In a Python program, the leading whitespace including spaces and tabs at the beginning of the
logical line determines the indentation level of that logical line.
The level of indentation groups statements to form a block of statements.
This means that statements in a block must have the same indentation level.
Python very strictly checks the indentation level and gives an error if indentation is not correct.
Illustration of indentation (voting.py)
age = int(input("Enter age: "))
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.
INPUT FUNCTION
input() 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:
<variable>= input([prompt])
Here,
The prompt is an optional parameter.
The prompt is an expression that serves to prompt the user for input. This is almost always a
string literal which is enclosed within quotes (single or double) with parentheses.
The result of input() function is returned a numeric value, and assigns to a variable.
When the input() function executes, it evaluates the prompt and displays the 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
raw_input()
The purpose of raw_input() function is to read input from the standard input stream (the keyboard,
by default). Using this function, we can extract string of characters (both alphanumeric and special).
Syntax:
<variable> = raw_input(['prompt'])
Here,
This function reads a line from input (i.e. the user) and returns a string by stripping a trailing newline.
It always returns a string.
Example:
Name = raw_input("Enter name:")
Address = raw_input('Enter address:')
To get an integer value using raw_input() function, you have to convert the input string into these
values into respective data types using int(), float(), etc.
Illustration of raw_input function
Num1 = int(raw_input("Enter first number:"))
Num2 = 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
Thank You