python:How to deal with the division of the int value becomes 0?

Published on:
Last updated:

This post is also available in: 日本語 (Japanese)

Integer division in python may result in 0 and the following error may be thrown
I wrote a note on how to deal with it.

# xxx is some variable
ValueError: xxx must be > 0

By default Python outputs 0 if the numerator is greater than the denominator.
As a workaround, it seems that the calculation result with a decimal point can be obtained by specifying to handle it as a float type or by multiplying it by 1.0 as shown below.

# The output is int type, no problem.
>>> 10/10
1
# There is a problem if the output is int type.
>>> 10/100
0
# A pattern that specifies handling in float type and sets the output to float type.
>>> float(10)/100
0.1
# A pattern that multiplies by 1.0 and makes the output a float type.
>>> 10*1.0/100
0.1
# By the way, in the following, the output of the calculation result 0 is converted to float type, so it becomes "0.0".
>>> float(10/100)
0.0
No tags for this post.

About
Kuniyoshi Takemoto is the founder of Amelt.net LLC, and editor of this blog(www.amelt.net).Learn more and follow me on LinkedIn.