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.

3
  • 2
    When you divide, the result is always a float Commented Jul 19, 2022 at 9:47
  • Are you actually looking for mathematically half the value? or would you like to remove the decimal point? Commented Jul 19, 2022 at 9:58
  • 1
    @FreddyMcloughlan I would like to delete the decimal point. Commented Jul 19, 2022 at 10:01

2 Answers 2

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'>
Sign up to request clarification or add additional context in comments.

2 Comments

Why don't you need the parentheses at if?
@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)
1

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

a //= 2

Comments