Python Operators and Errors
Grade 11 Computer Science Notes
Introduction to Operators
• Operators are symbols that perform
operations on variables and values in Python.
Arithmetic Operators
• Examples:
• a = 10, b = 3
print(a + b) → 13
print(a - b) → 7
print(a * b) → 30
print(a / b) → 3.33
print(a // b) → 3
print(a % b) → 1
Relational Operators
• Compare two values and return True/False.
• x = 5, y = 10
print(x > y) → False
print(x < y) → True
print(x == y) → False
print(x != y) → True
Logical Operators
• Used to combine conditions.
• a = True, b = False
print(a and b) → False
print(a or b) → True
print(not a) → False
Assignment Operators
• Used to assign values to variables.
• x=5
x += 2 → 7
x -= 1 → 6
x *= 3 → 18
x /= 2 → 9.0
Bitwise Operators
• Operate on binary values.
• a = 5, b = 3
print(a & b) → 1
print(a | b) → 7
print(a ^ b) → 6
print(~a) → -6
print(a << 1) → 10
print(a >> 1) → 2
Membership & Identity Operators
• Membership:
• nums = [1,2,3]
• print(2 in nums) → True
• Identity:
• x = [1,2,3], y = x
• print(x is y) → True
• print(x == y) → True
Errors in Python
• Errors are problems that stop program
execution.
• Types:
• 1. Syntax Errors
• 2. Runtime Errors (Exceptions)
• 3. Logical Errors
Syntax Error Example
• print('Hello' # Missing parenthesis
• Output: SyntaxError: unexpected EOF
Runtime Error Example
• a = 10, b = 0
• print(a / b)
• Output: ZeroDivisionError: division by zero
Logical Error Example
• total = 50, count = 10
• average = total * count # Wrong formula
• Output: 500 (instead of 5.0)
Error Handling Example
• try:
• num = int(input('Enter a number: '))
• print(10 / num)
• except ZeroDivisionError:
• print('Division by zero not allowed')
• except ValueError:
• print('Enter a valid number')