Python Programming - Important Questions with Answers
Q1: Explain the various categories of operators in Python.
Operators in Python are used to perform operations on variables and values. Categories include:
1. Arithmetic Operators: +, -, *, /, %, **, //
2. Comparison Operators: ==, !=, >, <, >=, <=
3. Logical Operators: and, or, not
4. Bitwise Operators: &, |, ^, ~, <<, >>
5. Assignment Operators: =, +=, -=, *=, etc.
6. Membership Operators: in, not in
7. Identity Operators: is, is not
Example:
a = 3, b = 5, c = 10
i) a & b < 2/5**2 + c^b
- Operator precedence is applied. First **, then /, ^, &, <, +.
ii) b >> a**2 >> b**2 ^ c**3
- Again, follow precedence: ** > >> > ^
Q2: What do you mean by operator precedence and associativity?
Operator precedence determines which operator is evaluated first in an expression.
Associativity determines the order in which operators of the same precedence are evaluated.
Example: a = 5 + 2 * 3
- Multiplication has higher precedence, so result is 5 + (2*3) = 11
- Example of associativity: a = 5 - 2 - 1 => (5 - 2) - 1 = 2