Day 3 was all about operators. Some of the results caught me off guard.
Arithmetic operators
no1, no2 = 10, 3
print(no1 + no2) # 13
print(no1 - no2) # 7
print(no1 * no2) # 30
print(no1 / no2) # 3.3333333333333335
print(no1 // no2) # 3 (floor division)
print(no1 % no2) # 1 (remainder)
print(no1 ** no2) # 1000 (power)
Fun one: you can multiply a string.
name = "sridhar"
print(name * 3) # sridhar sridhar sridhar
And dividing by zero gives a ZeroDivisionError, for both / and //.
Relational (comparison) operators
>, <, >=, <=, ==, !=
Strings are compared in dictionary order:
print('ajith' < 'ajithkumar') # True
Booleans are numbers underneath: True is 1, False is 0.
print(False < True) # True
Operator chaining was new to me:
no1, no2, no3 = 100, 200, 300
print(no3 > no2 > no1) # True
print(no3 > no2 < no1) # False (200 < 100 is false)
Logical operators: and, or, not
This one surprised me. and doesn't always return True or False:
print(10 and 20) # 20
print(not 'Vishnu') # False
print(not '') # True
A non-empty string counts as True and an empty string counts as False.
Assignment shortcuts
no1 = 5
no1 += 10 # same as no1 = no1 + 10
no1 -= 10
no1 *= 10
no1 **= 2
Bitwise (just a teaser)
print(4 & 5) # 4
print(4 | 5) # 5
Bits = binary digits.
Top comments (0)