- Cool stuff in Python
- You can test it in: https://paiza.io/en/projects/new?language=python3
- The results are commented for you to copy and paste in your preferred interpreter
- Yes, you can contribute with more tricks
The floor division operator is //
For example, the expression 11 // 4 evaluates to 2 in contrast to the 2.75 returned by float true division.
- Python3:
print ( 11//4 )
# 2
print( 11/4 )
# 2.75
Note that (-11) // 4 is -3 because that is -2.75 rounded downward
print ( -11//4 )
# -3
print ( -11/4 )
# -2.75
- Python2:
print ( 11//4 )
# 2
print ( 11/4 )
# 2
print ( -11//4 )
# -3
print ( -11/4 )
# -3
somevar = '*'
somevar *= 33
print(somevar)
# *********************************
The *= always calls imul on the left hand operand :
product = [1]
product *= 5
print ( product )
# [1, 1, 1, 1, 1]
is equivalent to :
product = [1]
product.__imul__(5)
print ( product )
# [1, 1, 1, 1, 1]
Tuple unpacking allows you to just pass a tuple or list to a function that expects several positional arguments; these then get unpacked accordingly.
For example:
- Python3:
print(*[1, 2, 3, 4])
# 1 2 3 4
print([1, 2, 3, 4])
# [1, 2, 3, 4]
- Python2:
print(*[1, 2, 3, 4])
# SyntaxError: invalid syntax
print([1, 2, 3, 4])
# [1, 2, 3, 4]
Different way to Round comparing Decimal to Float
For example:
- Python3:
from decimal import *
print ( Decimal('0.3') + Decimal('0.3') + Decimal('0.3') == Decimal('0.9') )
# True
print ( float('0.3') + float('0.3') + float('0.3') == float('0.9') )
# False