Session 2 of the DSMP Python track → operators, decision-making, modules, and loops. This is where code starts to do things.
Symbols that perform an operation on values. There are six families.
Arithmetic → the math ones:
print(5 + 6) # 11 addition
print(5 - 6) # -1 subtraction
print(5 * 6) # 30 multiplication
print(5 / 2) # 2.5 division (always gives a float)
print(5 // 2) # 2 floor division (drops the decimal part)
print(5 % 2) # 1 modulo (the remainder)
print(5 ** 2) # 25 power (5 squared)
Relational (comparison) → ask a true/false question, return a boolean:
print(4 > 5) # False
print(4 < 5) # True
print(4 >= 4) # True
print(4 <= 4) # True
print(4 == 4) # True (== checks equality, a single = assigns)
print(4 != 4) # False (!= means "not equal")
Logical → combine conditions:
print(1 and 0) # 0 true only if BOTH sides are true
print(1 or 0) # 1 true if AT LEAST ONE side is true
print(not 1) # False flips true ↔ false
Bitwise → work on the binary (bit) level. You'll use these rarely as a beginner:
print(2 & 3) # 2 AND
print(2 | 3) # 3 OR
print(2 ^ 3) # 1 XOR
print(~3) # -4 NOT
print(4 >> 2) # 1 right shift
print(5 << 2) # 20 left shift
Assignment → = stores a value. The compound ones update a variable in place:
a = 2
a %= 2 # short for: a = a % 2 → 0
print(a) # 0
The same shortcut works for +=, -=, *=, /=, **=, etc. Note: Python has no a++ or ++a.
Membership → check whether something sits inside a sequence:
print('D' not in 'Delhi') # False ('D' IS in 'Delhi')
print(1 in [2,3,4,5,6]) # False (1 is not in the list)
Practice program → sum of the digits of a 3-digit number. Uses % 10 to grab the last digit and // 10 to chop it off:
number = int(input('Enter a 3 digit number'))
a = number % 10 # last digit
number = number // 10
b = number % 10 # middle digit
number = number // 10
c = number % 10 # first digit
print(a + b + c) # e.g. 666 → 18