Page 98 - Information_Practice_Fliipbook_Class11
P. 98
4.5 Expressions
An expression in Python is a valid combination of constants, variables, and operators. A single value of any type or
the name of an object (i.e. a variable) are examples of the simplest expressions. On evaluation, an expression yields
a value. The type of an expression is based on the types of operators and operands that are used in it. An expression
yields a value, and the type of the value that an expression yields is called the type of the expression. Assuming that
the variables a, b, and num have values 5, 7, and 12.5 respectively, some examples of valid expressions are:
Expression Type
(i) 50 int
(ii) a int
(iii) a == 5 and b>0 bool
(iv) num + 45.6 - 6 float
(v) 22/7*2*2 float
(vi) "abc"*3 str
4.6 Precedence of Operators in Python
When an expression involves multiple operators, Python resolves the order of execution according to the precedence
of operators. An operator with higher precedence will be evaluated before an operator with lower precedence. As a
general rule, the unary operators have higher precedence over binary operators. Among the binary operators, the
table gives the precedence from highest to lowest.
Table 4.7: Precedence of Operators in Python
Order Of Operators Description
Precedence
1 ** Exponentiation
2 ~, +, - Complement, unary plus, and unary minus
3 *, /, //, % Multiply, divide, integer division, modulo
4 +, - Addition, subtraction
5 in, not in, is, is not, <, <=, >, Membership, identity and relational operators
>=,!=, ==
6 not, and, or Logical operators
7 =, %=, /=, //=, -=, +=, *=, **= Assignment operators
The parenthesis () is used to override the precedence of operators. For example, in the expression 4*(3+7), even
though the * operator has precedence over the + operator, the + operator will get precedence over the * operator
because the subexpression 3+7 is enclosed within parentheses. If two binary operators have the same precedence,
then the expression is evaluated from left to right. However, the binary operator ** is an exception to the general
rule and is evaluated right to left. Thus, the expression 2**3**3 would be evaluated as if it were parenthesized as
2**(3**3) and yield the value 134217728. All unary operators are evaluated from right to left. For example, the
expression not True yields True. Next, let us consider some more examples of expressions.
Evaluate the expressions given below:
(i) 45*6+3/5
Solution:
45*6+3/5
84 Touchpad Informatics Practices-XI

