user4916173
user4916173

Reputation:

(Python) Why is it returning 9.0 instead of 9?

Trying to make a simple counter in python for a project in a "Learn Python Book"

Brief: Write a program that counts for the user. Let the user enter the starting number, the ending number and the amount by which to count.

Problem: Ok so basically trying to make sure that if the user were to type
in (start at 2 and count to 17 in 2's) that the program would flag it up as not possible.

print ("Welcome to the program for those who are to lazy to count")
print ("You must be really really lazy too use this")

input ("\n Press any key to continue")

Num1 = int(input ("Please Enter Starting Number: \n"))
Num2 = int(input ("Please Enter Ending Number: \n"))
count = int(input ("Count up in: \n"))

differ = (Num2 - Num1)

test =(differ/count)

if isinstance(test,int):
 while (Num1 < Num2):
  Num1 += count
  print (Num1)   
  isinstance( test, int )
else:
    print ("Sorry Starting at",Num1,"You can not get to",Num2,"counting up by",count,)

(( I did some testing and found that the variable test was always coming back as a float.A whole number for example 9 would be 9.0 which would of course make my if statement false. Can anyone explain why this is occurring and how to fix/get around it?))

Upvotes: 0

Views: 1032

Answers (4)

wpercy
wpercy

Reputation: 10090

You should test to see if (differ % count) == 0 instead of checking to see if your test is an integer. The result of your division operation is always a float because python 3 defaults to floating point division. It can be forced to perform integer division with //.

See the python docs for modulo.

Upvotes: 5

ezig
ezig

Reputation: 1229

wilbur's answer is the best, but if you still want to use division instead of modulo, instead of checking if isinstance(test, int) which checks if test is really an integer type (which is not true for 9.0), you can try if test.is_integer() which will return True if it's a float with an integer value (which is true for 9.0).

This is not an approach you can count on because division with floats is imprecise. Using a modulo operator is a lot more reliable!

Upvotes: 1

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13171

Python 3 / always returns float. For integer division, use //.

Upvotes: 0

Makoto
Makoto

Reputation: 106430

Python 3 does floating-point division by default. If you want to force integer division, express double slashes in your quotient (differ // count).

Upvotes: 0

Related Questions