Python Fundamentals – Operators and Expressions
OPERATORS
An operator in Python, specifies an operation to be performed on the variables that yields a resultant value. An operand is an entity on which an operator acts. For example in the expression: a + b
the sign + is an operator which specifies the operation of addition on the two operands a and b.
Python language operators are classified into following types. These are:
(a) Arithmetic Operators
(b) Relational (Conditional) Operators
(c) Logical /Boolean Operators
(d) Assignment Operators
(e) Bitwise Operators
(f) Membership Operators
(g) Identity Operators
ARITHMETIC OPERATORS
Arithmetic operators, such as +, -,*,/, % (modulus), ** (exponent), etc., are used for mathematical calculations. An arithmetic expression is made up of constants, variables, a combination of both or a function call, connected by arithmetic operators. Some of these operators also work on data types other than numbers, but they may work differently. For example, + adds two numbers (2 + 2 gives the result 4). But con-catenating numbers as a strings (‘2’ + ‘2’ gives the result ’22’).
You can’t use an operator with two incompatible data types. For example, if you try to use + with an integer and a string, Python returns an error.
An arithmetic expression is made up of constants, variables, a combination of both or a function call, connected by arithmetic operators.
Normally, operators are said to be either unary or binary. A unary operator has only one operand while a binary operator has two operands. In its unary mode with a single operand, a minus sign is usually a sign changing operator, while in its binary mode with two operands, a minus sign is usually a subtraction operator.
Working with Arithmetic Operators
The binary arithmetic operator requires two operands to operate upon them. Assume variable a holds 10 and variable b holds 20 then:
(a) + (addition or plus) say a + b will give 30
(b) – (subtraction or minus) say a – b will give -10
(c) * (multiplication) say a * b will give 200
(d) / (slash for division) say b / a will give 2
(e) % (modulus operator for remainder), say b % a will give 0
(f) ** (exponent – Performs exponential (power) calculation on operators)
a = 2
b = 3
c = a**b will give 8
(g) // (Floor division) – The division of operands where the result is the quotient in which the digits after the decimal point are removed.
a=9
b=2
9//2 will give 4
and
a=9.0
b=2.0
9.0//2.0 will give 4.0
Example 1
# Demo of: arithmetic operators a = 20 b = 10 c = 0 c = a + b print "Sum of a + b is ", c c = a - b print "Difference a - b is ", c c = a * b print "Multiplication a * b is ", c c = a / b print "Division a/b is ", c c = a % b print "Remainder a%b is ", c a = 2 b = 3 c = a**b print "Exponentiation a**b is ", c a = 10 b = 5 c = a//b print "Integer division a//b is ", c RUN Sum of a + b is 30 Difference a - b is 10 Multiplication a * b is 200 Division a/b is 2 Remainder a%b is 0 Exponentiation a**b is 8 Integer division a//b is 2
Hierarchy of Arithmetic Operators
Operations in Python happen in a specific order, which is called operator precedence. As in arithmetic, operations in parentheses come first. Operators in higher rows are evalu¬ated before operators in lower rows. If multiple operators appear in a single cell in the table, that means they are equal in precedence and are evaluated from left to right when they appear in an expression.
When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS (Parentheses Exponentiation Multiplication Divi¬sion Addition and Subtraction) is a useful way to remember the rules. The hierarchy or order of operation of arithmetic operators is as follows:
- Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (4-1) is 6, and (l+l)**(5-2) is 8. You can also use parentheses to make an expression easier to read.
- Exponentiation has the next highest precedence and evaluated from right to left, 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 when you have a multiple expression like 2*3-1 multiplication, and division are performed before addition and subtraction so the result is 5, not 4, and 6+4/2 is 8, not 5.
- Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression degrees / 2 * pi, the division happens first and the result is multiplied by pi. To divide by 2n, you can use parentheses or write degrees / 2 / pi.
Example 2
Integral Division and Remainder
When both operands of the division operator (/) are integers, the result is an integer. If operands are positive and the division is imprecise, the fractional part is truncated. Note that combining an int with an int produces an int. Combining float with another float creates another float. But if we have two values one int and other float, i.e., mixed typed expressions, Python will automatically convert ints to floats and perform floating point operations to produce a float result.
For example:
Python also provides int() and long() functions that can be used to convert numbers into ints and longs, respectively. Converting to an int or long int simply discards the fractional part of a float, the value is truncated, not rounded. For example,
››› int(4.5) 4 ›››int(3.9) 3 ››› long(3.9) 3L ›››float(int(3.3)) 3.0 ››› int(float(3.3)) 3 ›››int(float(3)) 3
Example 3
Given the following declarations:
int m = 3, n = 4; float x = 2.5, y = 1.0;
Evaluate the values for the following expressions:
(a) m + n + x + y
(b) m + x * n + y
(c) x / y + m / n
(d) x-y*m + y/ n
(e) x / 0
Solution
- The expression (m + n + x + y) is equal to 3 + 4 + 2.5 + 1.0 = 10.5.
- The expression (m + x * n + y) is equivalent to ((m + (x * n) + y)) because the hierarchy of * is higher than that of +. Substituting the values of the variables, we get:
((3 + (2.5 * 4) + 1.0)) = 14.0 - The expression (x / y + m / n) is equivalent to ((x / y) + (m / n)). Thus, substituting the values of x, y, m and n, we get:
(2.5 / 1.0) + (3 / 4) = 2.5 - The expression (x – y * m + y / n) is equivalent to (x – (y * m)) + (y / n). Thus, substituting the values of x, y, m and n, we get:
(2.5 – (1.0 * 3) + (1.0 / 4)), i.e., 2.5 – 3.0 + .25, i.e., -0.25. - x / 0 is undefined. Any number divided by zero is infinite and hence the value is not defined so you will get error message.
Remainder Operator (%)
Unlike the other arithmetic operators, which accept both integer and floating point operands, the remainder operator (also called the modulus operator) accepts only integer value of operands. The resulting value is the remainder of the first operand divided by the second operand. For example, the expression:
9 % 5
has a value of 4 because 5 goes into 9 once with a remainder of 4. The expression:
10 % 5
has a value of zero because 5 goes into 10 two times with no remainder.
RELATIONAL / CONDITIONAL OPERATORS
Relational/conditional operators are used to test the relation between two values. All Python relational operators are binary operators and hence require two operands. A relational expression is made up of two arithmetic expressions connected by a relational operator. Comparison operators produce a Boolean result (type bool, either True or False). When a Boolean expression is evaluated, it produces a value of either true (the condition holds) or false (it does not hold). Conditions may compare either numbers or strings. If you compare strings, you get result based on alphabetical order. For example, “apple” < “orange” is true, because “apple” is alphabetically less than “orange”.
When comparing strings, the ordering is lexicographic. Basically, this means that strings are put in alphabetic order according to the underlying ASCII (American Standard Code for Information Interchange) codes. So all upper-case letters come before lower case letters (For example, Bbbb, comes before aaaa, since B precedes a).
The list of relational operators is given in Table 11.1
For example,
›››5 < 8 True ››› 5 < 3 False ››› 5 < 7 < 10 True ››› "Apple" < "Mango" True ›››"Orange" < "Mango" False ›››7 > 3 True ›››5 <= 8 True ››› 7 <= 5 False ››› 51=6 True ›››4 != 4 False ››› 5==5 True >» 4 = = 5 False ›››'Good' == 'Good' True ››› 'Good' == 'Very Good' False
All the relational operators have lower precedence than the arithmetic operators. For example, the expression:
a + b*c<d / f
is evaluated as if it had been written as follows:
(a +(b*c ))<(d/f)
Example 4
Consider the following declarations:
j = 0
m = 1
n = -1
x = 2.5
y = 0.0
Evaluate the following expressions:
(a) j > m
(b) m / n < x
(c) j <= m >= n
(d) -x + j == y > n >= m
Solution
- j > m is not true because the value of j = 0 and value of m = 1. Hence the result is False.
- The expression m / n < x is equivalent to (m / n) < x because the hierarchy of / is higher than that of <. Substituting the values of the variables, we get the result True.
- The expression j <= m >= n is equivalent to ((j <= m) >= n). Substituting the values of the variables we get the result as True.
- The expression -x +j == y > n >= m is equivalent to ((-x) +j ) == ((y > n) >= m). Substituting the values of the variables we get the result as False.
LOGICAL/BOOLEAN OPERATORS
Logical/Boolean operators combine the results of one or more expressions and these are called logical expressions. After testing the conditions, they return logical status True or False. Python tests an expression with and and or operators from left to right and returns the last value tested.
There are three logical operators: and, or, and not.
and
If both the operands are true then condition becomes true. Logical and stops testing when it encounters a false condition. For example, x > 0 and x < 10 is true only if x is greater than 0 and less than 10.
or
If any of the two operands is true, then condition becomes true. Logical or stops testing when it encounters a true condition. For example n%2 == 0 or n%3 == 0 is true if either of the conditions is true, that is, if the number is divisible by 2 or 3.
not
Logical not operator use to reverses the logical state of its operand. If a condition is true then logical not operator will make false. Logical not returns True if the expression is false and False if the expression is true. For example, the not operator negates a boolean expression, so not (x > y) is true if x > y is false, that is, if x is less than or equal to y. Comparisons may be combined using the Boolean operators and and or, and the out¬come of a comparison may.be negated with not. These have lower priorities than comparison operators.
Hierarchy of Logical Operators
The logical not operator has a higher precedence than the others. The and operator has higher precedence than the or operator. Both the logical and & or operators have lower precedence than the relational and arithmetic operators precedence than the relational and arithmetic operators.
Example 5
Consider the following declarations:
j = 0
m= 1
n = -1
Evaluate the following expressions:
(a) j and m
(b) j < m and n <m
(c) m + n or not j
Solution
- j and m is not true because the value of j = 0 and the value of m = 1. Hence the result is 0 (zero).
- The expression j < m and n < m is equivalent to (j < m) and (n < m) because the hierarchy of relational operators is higher than that of logical operators. Substi-tuting the values of the variables we get the result to be true.
- The expression m + n or not j is equivalent to (m + n) or (not j). Substituting the values of the variables we get the result to be true.
PRECEDENCE OF OPERATORS
All operators have two important properties called precedence and associativity. Both properties affect how operands are attached to operators. Operators with higher precedence have their operands bound or grouped to them before operators of lower precedence, regardless of the order in which they appear. For example, the multiplication operator has higher precedence than the addition operator, so the two expressions:
2 + 3*4 3*4 + 2
both evaluate to 14-the operand 3 is grouped with the multiplication operator rather than the addition operator because the multiplication operator has a higher precedence. If there were no precedence rules, and operators are grouped with operands from left- to-right order, then the first expression will be evaluated.
2 + 3*4
to 20 which is not correct.
Right-to-left associativity means that the compiler starts on the right of the expression and works towards left. Left-to-right associativity means that the compiler starts on the left of the expression and works towards right.
For example, the plus and minus operators have the same precedence and are both left- to-right associative. For example, in the expression:
a + b - c
The expression is evaluated as: add a to b, then subtract c
The assignment operator, on the other hand, is right-associative. For example in the expression:
a = b = c
The expression is evaluated as:
assign c to b, then assign b to a
When mathematical operations are performed with mixed operators in Python expres¬sion, Python uses rules and regulations to determine which operations to perform first, based on a pre-determined precedence. The rule of operator precedence follows a similar precedence as applied in most computer programming languages. Table 11.2 summarizes the operator precedence applied in Python programming.
ASSIGNMENT (AUGMENTED) OPERATORS
Assignment operator combines the effect of arithmetic and assignment operator. Augmented assignments can make your code more compact, concise, and more readable. Instead of writing x = x + 1, you can just put the expression operator (in this case +) before the assignment operator (=) and write x += 1. This is called an augmented assignment, and it works with all the standard operators, such as *, /, %, and so on.
For example,
››› x = 2 ›››x += 1 ››› x *= 2 ››› x 6
Python language offers special shorthands that combine assignment with each of the arithmetic operations to simplify the coding. The operators are given in Table 11.3. The equivalences are shown in Figure 11.4.
For example, the expression:
j = j * 5 can be written as j *= 5
One of the main reasons for using the arithmetic assignment operators is to avoid spelling mistakes and make code more readable. For example, the expression:
op_big_x_dimension = op_big_x_dimension * 2 can be written as op_big_x_dimension *= 2 *,
The second version is easier to read and to write and contains fewer opportunities for spelling errors.
The assignment operators have relatively low precedence. This leads to interesting con-sequences. For example, the following two expressions are not the same:
j = j * 3 + 4 j *= 3 + 4
The addition operator has higher precedence than the assign operator, and the multiplication operator has higher precedence than the addition operator, so the two expressions are interpreted as follows:
Example 6
# Demo of assignment operator a = 2 b = 10 c = 0 c = a + b print "Value of c is ", c c += a print "Value of c += a (add-assign) is ", c c *= a print "Value of c *= a (multiply-assign) is ", c c /= a print "Value of c /= a (divide-assign) is ", c c **= a print "Value of c **= a (exponential assign) is ", c c //= a print "Value of c //= a (integer division assign) is ", c c %= a print "Value of c %= a (remainder-assign) is ", c RUN Value of c is 12 Value of c += a (add-assign) is 14 Value of c *= a (multiply-assign) is 28 Value of c /= a (divide-assign) is 14 Value of c **= a (exponential assign) is 196 Value of c //= a (integer division assign) is 98 ’ Value of c %= a (remainder-assign) is 0
Figure 11.4 Demo of assignment operator
BITWISE OPERATORS
A bit is the smallest possible unit of data storage, and it can have only one of the two values : 0 and 1. Bitwise operator works on bits and perform bit-by- bit operation.
Table 11.4 shows the bitwise operators and their meaning.
In order to understand the bitwise operators, let us consider first the SHIFT operations. There are two types of shift operators that shift the bits in any integer variable by a specified number of positions. The ‘»’ operator shifts bits to the right, and the ‘«’ operator shifts bits to the left.
The Right Shift Operator ‘>>’
The right shift (>>) shifts the bits of the number to the right by the number of bits specified.
In general, the right shift operator is used in the form:
variable »number-of-bits
11>> 1 gives 5.11 is represented in bits by 1011 which when right shifted by l-bit gives 101 which is the decimal 5. Take another example, we know that the decimal number 8 is represented in binary form as:
1000
Similarly, the decimal number 4 is represented as:
100
If we represent data in a computer using 8 bits form, then decimal digits 8 and 4 will be represented by 00001000 and 00000100, respectively. The only difference between these two numbers is that the “1” in the second number is shifted one bit to your right. If the variable “a” holds the value “8”, then you can shift it right one position, by the statement:
a »1
This expression when converted to decimal value would be evaluated as “4”. You can shift a number by several bits. For example, you can change “8” into “2” by shifting the digit T’ by two bits to the right by using the expression:
a »2 .
Left Shift Operator«’
The left shift («) operator shifts bits to the left for a specified number of bit positions. Each number is represented in memory by bits or binary digits, i.e., 0 and 1. The expres-sion takes the form:
variable« number-of-bits 2 « 2 gives 8.
2 is represented by 10 in bits. Left shifting by 2 bits gives 1000 which represents the dec-imal 8.
& (Bitwise AND)
Bitwise AND of the numbers 5 & 3 gives 1.
!! (Bitwise OR)
Bitwise OR of the numbers 5 ” 3 gives 7.
∧ (Bitwise XOR)
Bitwise XOR of the numbers 5 A 3 gives 6.
~ (bit-wise invert)
The bitwise inversion of x is -(x+1) ~5 gives -6.
MEMBERSHIP OPERATORS
Python has membership operators, which test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators explained below:
in Operator
Evaluates to true if it finds a variable in the specified sequence and false otherwise. For example, x in y, here in results in a 1, if x is a member of sequence y.
not in Operator
Evaluates to true if it does not find a variable in the specified sequence and false other-wise. For example,
x not in y, here not in results in a 1, if x is not a member of sequence y.
Example 7
Boolean test whether a value is inside a container:
››› t = [1, 2, 4, 5] ››› 3 in t False ››› 4 in t True ››› 4 not in t False For strings, tests for substrings ››› a = 'abode' ›››'c' in a True ››› 'cd' in a True
IDENTITY OPERATORS
Identity operators compare the memory locations of two objects. There are two Identity operators explained below:
is Operator
Evaluates to true if the variables on either side of the operator point to the same object and false otherwise, x is y, here is results in 1 if is(x) equals is(y).
›››x=y= [i, 2, 3] ››› z=[1,2,3] ›››x==y True ››› x==z True = ››› x is y True ›››x is z False ››› X = [1, 2, 3] ››› y = [2, 4] ››› x is not y True
is not
Evaluates to false if the variables on either side of the operator point to the same object and true otherwise, x is not y, here is not results in 1, if is(x) is not equal to is(y).
EXPRESSIONS
Expressions consist of combinations of values, which can be either constant values, such as a string (“Shiva”) or a number (12), and operators , which are symbols that act on the values in some way. The following examples are expressions:
10-4 11 * (4 + 5) x - 5 a / b
An expression consists of one or more operands and zero or more operators linked together to compute a value. For example:
a + 2
is a legal expression that results in the sum of the value in the variable a and 2. The variable a is also an expression as is the constant 2, since they both represent the value. Expression values in turn can act as, Operands for Operators. For example, 9+6 and 8+5+2 are two expressions which will result into value 15. Taking another example,
б. 0/5+(8-5.0) is an expression in which values of different data types are used. These type of expressions are also known as mixed type expressions. When mixed type expres-sions are evaluated, Python promotes the result of lower data type to higher data type,
i. e., to float so, the result of above expression will be 4.2. This is known as implicit type casting. Implicit type casting is done without any intimation to the user. Sometimes we may want to perform a type conversion overselves. The programmer may instruct the Python interpreter to convert one type of data to another type, which is known as explict conversion. The float() function converts an int into float. Python also provides int() and long() functions that can be used to convert numbers into ints and longs, respectively. For example,
›››float(22) 22.0 ››› int (4.8) 4 ››› long(5.9) 5L
Expression can also contain another expression. When we have an expression consisting of sub expression(s), Python decides the order of operations based on precedence of operator. Higher precedence operator is worked on before lower precedence operator. Operator associativity determines the order of evaluation when they are of same precedence, and are not grouped by parenthesis. An operator may be left associative or right associative. In left associative, the operator falling on left side will be evaluated first,
while in right associative operator falling on right will be evaluated first. In Python and ‘**’ are right associative. The following list describes the basic rules of operator pre-cedence in Python:
- Expressions are evaluated from left to right.
- Exponents, multiplication, and division are performed before addition and sub-traction.
- Expressions in parentheses are performed first.
- Mathematical expressions are performed before Boolean expressions ( and , or , not) statements.
Table 11.5 Precedence of Operators from High Precedence to Low Precedence
STATEMENTS
A Python statement is a unit of code that the Python interpreter can execute. In computer language complete command is called statement. Examples of statement are:
››› print 12 + 15 27
This is because you told the system to print the result of the expression 12 + 15, which is a complete statement. However, if you type :
››› print 12 +
you will get a syntax error.
Other statements could be the following:
›››print "Welcome to the world of Python"
Welcome to the world of Python
››› print "Sum of 2 + 5 = ", 2+5 Sum of 2 + 5 = 7
The first statement asks python to display string literal Welcome to the world of Python. In second print statement Python prints the part of quotes “Sum of 2 + 5 = ” followed by the result of adding 2 + 5, which is 7.
To print multiple items in same line, separate them with comma.
It is possible to have a single statement span multiple lines when the line is too long to read on one screen. To do this, simply put a space and a backslash at the end of the line as explained earlier.
Note that Python allows you to put multiple statements on a line by separating each statement with a semicolon:
›››x = 1; y = 2
Input Statements
The purpose of an input statement is to get some information from the user of a program and store it into a variable. Some programming languages have a special statement to do this. In Python, input is accomplished using input() or raw-input() functions.
The difference between the two is that raw_input accepts the data coming from the input device as a raw string, while input accepts the data and evaluates it into python code. This is why using input as a way to get a user string value returns an error because the user needs to enter strings with quotes.
It is recommended to use raw_input at all times and use the int function to convert the raw string into an integer.
input( )
In Python, input is accomplished using an assignment statement combined with a spe¬cial expression called input(). Syntax of inputf) is as follows:
variable = input(<prompt>)
Here, prompt is an expression that serves to prompt the user for input; this is almost always a string literal (i.e., some text inside of quotation marks). When Python encounters an input expression, it evaluates the prompt and displays the result of the prompt on the screen. Python then pauses and waits for the user to type an expression and press the Enter key. The expression typed by the user is then evaluated to produce the result of the input. As the input provided is evaluated, it expects valid Python expression. If the input provided is not correct then either syntax error or exception is raised by Python.
››› print “Welcome to the world of Python”
Welcome to the world of Python
str = input("Enter your name: ") Enter your name: "Shashi"
Note that if you enter name with in quotation mark then it will accept, but if you write same statement without quotation mark, it will display an error,
str = input("Enter your name: ") Enter your name: Shashi
Traceback (most recent call last):
File “<pyshell#2>”, line 1, in <module> str = input(“Enter your name: “)
File “<string>”, line 1, in <module>
NameError: name ‘Shashi’ is not defined
›››x = input("x: ") x: 34 ››› y = input("y: ") y: 42 ›››print x * y 1428
Here, the statements at the Python prompts (›››) could be a part of a finished program, and the values entered (34 and 42) would be supplied by some user. Your program would then print out the value 1428, which is the product of the two.
raw_inpu( )
The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing newline). You can use the int() built-in function to convert any numeric input string to an integer representation.
str = raw_input("Enter your input: "); print "Received input is : ", str
This would prompt you to enter any string and it would display same string on the screen.
Enter your input: Hello Python! Received input is : Hello Python! Now type the following: ›››price = raw input ('Enter price: ') Enter price: 12.99 . ›››qty = raw_input('Enter quantity: ') Enter quantity: 3 ››› price * qty Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can't multiply sequence by non-int of type 'str'
It will display an error message, because price and qty are strings. This is because the raw_input() function always returns a string. In order to multiply them, you need to turn them into numbers. Let us check their datatype using type() function.
››› price, type(price) ('12.99', <type 'str'>) ››› qty, type(qty) ('3', <type 'str'>)
Here’s how you do it:
›››price = float(price) ›››qty = int(qty) ››› price * qty 38.969999999999999
Solved Exercise
Question 1.
Computer programs are composed of expressions, which are made up of statements.
True or False?
Answer:
False. Just the reverse is true. Programs are made up of statements, which are com¬posed of expressions.
Question 2.
In the following expression, 2+5, what is the common jargon for the plus sign, and what is the common jargon for the 2 and the 5?
Answer:
The plus sign is commonly called the operator. The 2 and the 5 are commonly called operands. More specifically, the 2 is the left operand and the 5 is the right operand.
Question 3.
Integer division produces a decimal result. True or False?
Answer:
False. Integer division produces an integer result.
Question 4.
The modulus operator is used to produce the quotient in division. True or False?
Answer:
False, the modulus operator is used to produce the remainder.
Question 5.
Describe the use of parentheses in expressions.
Answer:
Parentheses can be used to group terms in an expression in order to provide control over the order in which the operations are performed.
Question 6.
Describe how Python evaluates an expression containing parentheses.
Answer:
A Python expression is evaluated by first evaluating each of the sub-expressions in the parentheses, and then using those values to complete the evaluation. If the expression contains nested parentheses, the evaluation is performed by evaluating the innermost parentheses first and working outwards from there.
Question 7.
Explain the use of the assignment operator.
Answer:
The assignment operator causes the value of its right operand to be stored in the memory location identified by its left operand.
Question 8.
Which type usually provides the greater range for storage of numeric values, integer or floating point?
Answer:
Floating point usually provides the greater range for storage of numeric values.
Question 9.
What is difference between Operators and Expressions?
Answer:
Most statements (logical lines) that you write will contain expressions. A simple example of an expression is 2 + 3. An expression can be broken down into operators and operands.
Operators are functionality that do something and can be represented by symbols, such as + or by special keywords. Operators require some data to operate on and such data is called operands.
Question 10.
What is difference between * and ** ? Explain with an example.
Answer:
* (multiply) gives the multiplication of the two numbers or returns the string repeated that many times. For example,
2*3 gives 6.
‘la’ * 3 gives ‘lalala’.
** (power) returns x to the power of y. For example,
3 ** 4 gives 81 (i.e., 3 * 3 * 3 * 3)
Question 11.
What is difference between 1,11 and % operators?
Answer:
/ (divide) Divide x by y. For example:
4/3 gives 1.3333333333333333.
/ / (floor division) Returns the floor of the quotient. For example:
4 / / 3 gives 1
% (modulo) Returns the remainder of the division. For example:
8 % 3 gives 2.
-25.5 % 2.25 gives 1.5.
Question 1.
What is difference between «(left shift) and» (right shift) operators?
Answer:« (left shift) Shifts the bits of the number to the left by the number of bits specified.
(Each number is represented in memory by bits or binary digits i.e., 0 and 1)
2 « 2 gives 8. 2 is represented by 10 in bits.
Left shifting by 2 bits gives 1000 which represents the decimal 8.
» (right shift) Shifts the bits of the number to the right by the number of bits specified.
11» 1 gives 5.
11 is represented in bits by 1011 which when right shifted by 1 bit gives 101 which is the decimal 5.
Question 13.
What is difference between & (bit-wise AND), and | (bit-wise OR) operators?
Answer:
& (bitwise AND) Bitwise AND of the numbers 5 & 3 gives 1.
| (bitwise OR) Bitwise OR of the numbers 5 | 3 gives 7.
Question 14.
Explain not (boolean NOT) with an example.
Answer:
If x is True, it returns False.
If x is False, it returns True, x = True; .
not x returns False.
Question 15.
Explain and (boolean AND) with example.
Answer:
x and y returns False if x is False, else it returns evaluation of y
x = False;
y = True;
x and y returns False since x is False.
In this case, Python will not evaluate y since it knows that the left hand side of the ‘and’ expression is False which implies that the whole expression will be False irre-spective of the other values.
Question 16.
Explain or (boolean OR) with example.
Answer:
If x is True, it returns True, else it returns evaluation of y x = True; y = False;
x or y returns True.
Question 17.
Explain Associativity of operators with example.
Answer:
Associativity Operators are usually associated from left to right. This means that operators with the same precedence are evaluated in a left to right manner. For example, 2 + 3 + 4 is evaluated as (2 + 3) + 4.
Some operators like assignment operators have right to left associativity i.e. a = b = c is treated as a = (b = c).
Question 18.
What is the use of print statement?
Answer:
To print the result of calculations in a Python program to a terminal window, we apply the print command, i.e., the word print followed by a string enclosed in quotes, or just a variable:
Question 19.
What is an expression?
Answer:
An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions (assuming that the variable x has been assigned a value):
17 x x + 17
Question 20.
What is a statement?
Answer:
A statement is a unit of code that the Python interpreter can execute.
Question 21.
What do you mean by floor division?
Answer:
The operation that divides two numbers and chops off the fraction part. For exam¬ple, a=15.9, b= 3, c=a/ /b gives value 5.0 not 5.3.
Question 22.
What is difference between “=” and “==”?
Answer:
“=” is the assignment operator whereas “==” is the equality operator. The assignment operator is used to assign a value to an identifier, whereas the equality operator is used to determine if two expression have the same value.
Question 23.
What is the use of comment?
Answer:
Comments are the entry in a computer program for the purpose of documentation or explanation. Comments should be written so that the logic of a program become understandable easily. The compiler ignores comments.
Question 24.
Differentiate between comment and indentation.
Answer:
Comment is to provide internal documentation to a program whereas indentation makes a program or a function clear and readable.
Question 25.
What do you mean by precedence and associativity of operators?
Answer:
The operators with Python are grouped hierarchically according to their precedence (i.e, order of evaluation) operations with a higher precedence are carried out before operations having a lower precedence. Assignment operators have a lower prece¬dence than any of the other operators.
The order in which consecutive operations within the same precedence group are carried out is known as associativity. *-
Question 26.
Determine the hierarchy of operations and evaluate the following expression:
I = 2*3/4 + 4/8 + 8-2 + 5/8
Answer:
Here, * will be performed before / even though * and / has same priority. This is because * occurs prior to the / operator.
= 6/4+ 4/8+ 8-2+ 5/8
= 1 + 4/8 + 8-2 + 5/8
= 1 + 0 + 8-2 + 5/8
= 1 + 0 + 8-2 + 0
=l+8-2+0
=9-2+0
= 7 + 0
= 7
Question 27.
Write a short note on identifiers.
Answer:
Identifier is the user-defined name given to a part of a program viz. variable, object, function etc. Identifiers are not reserved. These are defined by the user and they can have letters, digits and a symbol underscore. They must begin with either a letter or underscore. For instance, _chk, chess, trial etc. are valid identifiers.
Question 28.
Write short note on raw_input()
Answer:
raw_input(prompt) gets input from the user, as a string. You can use the int() built-in function to convert any numeric input string to an integer representation.
Multiple Choice
Question 1.
Operator precedence determines which operator:
(a) Operates on the largest numbers
(b) Is used first
(c) Is most important
(d) None of these
Answer: (b)
Question 2.
Indicate which of the following is true about ‘Python’ operators:
(a) Operators must have one or more operands
(b) Operators are either unary or binary
(c) Operators have some precedence
(d) All of the above
Answer: (d)
Question 3.
Escape sequence:
(a) \n
(b) V
(c) \a
(d) \”
Answer: (d)
Question 4.
The expression, i=30*10+27; evaluates to:
(a) 327
(b) -327
(c)810
(d)0
Answer: (a)
Question 5.
Identity operators:
(a)is
(b)Both (a) and (b)
(c)is not
(d)None of the above
Answer: (c)