Search code examples
pythonnumpynumpy-random

If-Else statement works weird in Python


import numpy as np 
import sklearn 
import sklearn.datasets
from sklearn import svm
x = np.array([1,3,67,8])
print(x)
print(type(x))

if type(x) != int:
    y = x.astype(int)
    print(y)
    print(type(y))
else:
    print ("X is already an integer")

This is my code here if x is not integer then convert it to integer else print it as integer but it works weirdly that code in if statement is executed even if x is integer or float.


Solution

  • I believe this is what you are looking for. To check whether a value is an integer (even if in a float array), then you can test x == int(x).

    import numpy as np 
    
    arr = np.array([1, 3, 67, 8, 7.5])
    
    print(arr, type(arr))
    
    for x in arr:
        if x != int(x):
            y = x.astype(int)
            print(y, type(y))
        else:
            print(str(int(x)) + ' is already an integer')
    
    # [  1.    3.   67.    8.    7.5] <class 'numpy.ndarray'>
    # 1 is already an integer
    # 3 is already an integer
    # 67 is already an integer
    # 8 is already an integer
    # 7 <class 'numpy.int32'>