DEV Community

sridhar n
sridhar n

Posted on

Python Day 3 – Operators (and a Few Surprises)

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)
Enter fullscreen mode Exit fullscreen mode

Fun one: you can multiply a string.

name = "sridhar"
print(name * 3)   # sridhar sridhar sridhar
Enter fullscreen mode Exit fullscreen mode

And dividing by zero gives a ZeroDivisionError, for both / and //.

Relational (comparison) operators

>, <, >=, <=, ==, !=

Strings are compared in dictionary order:

print('ajith' < 'ajithkumar')   # True
Enter fullscreen mode Exit fullscreen mode

Booleans are numbers underneath: True is 1, False is 0.

print(False < True)   # True
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Bitwise (just a teaser)

print(4 & 5)  # 4
print(4 | 5)  # 5
Enter fullscreen mode Exit fullscreen mode

Bits = binary digits.

Top comments (0)