0

Consider this input code to find half of the number that you input:

>>> a = int(input("Please input a number: "))
Please input a number: 4
>>> if(a/2 == a/2):
...     a/=2
...     print("Half of the number than you input is:",a)
...
Half of the number than you input is: 2.0

When I input it, it was a int, but why has it changed from int to float? Note: If I enter numbers that requires to print out decimal points such as 5, it will print 2.5.

2 Answers2

3

Unlike other languages, Python3 does not keep the result of int/int as an int. Python3 always returns a float.

You need to use the integer division operator (// or //=)

What is the difference between '/' and '//' when used for division?

Why does integer division yield a float instead of another integer?

I will keep the previous answer below


If you would like to cast "integer like" decimals, use is_integer:

a = int(input("Please input a number: "))
a /= 2
if a.is_integer():
    a = int(a)

print(a)

is_integer

Return True if the float instance is finite with integral value, and False otherwise:


Test table:

Input Output type()
0 0 <class 'int'>
1 0.5 <class 'float'>
2 1 <class 'int'>
-1 -0.5 <class 'float'>
-2 -1 <class 'int'>
0 0 <class 'int'>
1.0 0.5 <class 'float'>
2.0 1 <class 'int'>
-1.0 -0.5 <class 'float'>
123 61.5 <class 'float'>
Freddy Mcloughlan
  • 4,129
  • 1
  • 13
  • 29
  • Why don't you need the parentheses at `if`? –  Jul 19 '22 at 10:04
  • @scissors127 Python does not need to contain the *whole condition* in parenthesis. But you may use it in cases like `(a and b) or c` which is equivalent to `((a and b) or c)` – Freddy Mcloughlan Jul 19 '22 at 10:13
1

If you only want the integer part of the division, use the floordiv operator:

a //= 2
Richard Neumann
  • 2,986
  • 2
  • 25
  • 50