Skip to content

mitgate/python-cool-stuff

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

25 Commits
 
 

Repository files navigation

python-cool-stuff

Mathematical division that rounds down to nearest integer.

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 

Combined multiply and assignment

somevar = '*' 
somevar *= 33
print(somevar)
# *********************************

Some things Under the hood

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

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]

Auto Rounding

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

About

Cool stuff in Python

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •