2

My problem is when I divide a number like: 10 / 2 → integer / integer.

The result is 5.0 and it is float, but it shouldn't be float. The problem is Python adds 0.0 to every number accept to divide with the second number.

So I want 10/2 be integer.

I tried

x = 10
y = x/2
type(y) == int

It prints false. I want type(y) print the true result although x was a prime or odd number.

1
  • 1
    Why do you need the result to be an int? Commented Nov 7, 2015 at 21:24

1 Answer 1

5

/ gives a floating point result. If you want an integer result, use //.

The reason it works like this is that if you have something like

function1() / function2()

it is possible to tell the type of the result even if you don't know the types returned by the individual functions.

Edit 1

Note that it has not always been this way. This is a "new" Python 3 behaviour, also available (but not active by default) for Python 2.2 onwards - see PEP 238. Thanks to @Steve314 for pointing this out.

Edit 2

However, it seems that what you are really trying to do is tell if one number goes exactly into another. For this you should use % (remainder)

print(15 % 5 == 0) 
print(16 % 3 == 0)

This prints

True
False

Edit 3

If you want the type of the result to depend on whether the division goes exactly, you would need to do

a // b if a % b == 0 else a / b 
Sign up to request clarification or add additional context in comments.

12 Comments

it tried to divide for exp : x= 10 / 5 type(x) == int and it's print false it should be int
I tried x = 10 y= x/2 type(y)== int it print false
@user_user Try x = 10 y = x // 2 print(type(y) == int). You should get true.
ok when I change x to x=9 y= x//2 type(y)== int it will be true and it is false
@user_user When you do // the result is an int, even if the second number does not go exactly into the first. I think it works by dividing the numbers and rounding down to an integer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.