Edin Mahmutovic
Edin Mahmutovic

Reputation: 117

Integer input intepreted as a float

I'm having an interactive menu where the user has to edit some numbers if the numbers are floats or not a subset of a given list. The following code is used:

grades = np.array([-3,-10.5,0,7,4,8,4,7,10,5])
SevenGradeScale = np.array([-3, 0, 2, 4, 7, 10, 12])
for i in range(np.size(grades)):
    if grades[i] not in SevenGradeScale:
        while True:
            if type(grades[i]) is np.float64:
                print("{:f} is not a valid grade. The grade must be an integer.".format(grades[i]))
            elif type(grades[i]) is np.int32:
                print("{:d} is not within the seven grade scale.".format(grades[i]))
            else:
                type("{:f} is not a valid grade.".format(grades[i]))
            #try:
            grades[i] = input("Insert new grade: ")

And what I'm trying to do is, that the user edits the number that the script sees as invalid. But when trying to type in an integer, I get a float back. Why is that?

-10.500000 is not a valid grade. The grade must be an integer.

Insert new grade: 10
10.000000 is not a valid grade. The grade must be an integer.

Insert new grade: 

Upvotes: 2

Views: 78

Answers (2)

Julian Rachman
Julian Rachman

Reputation: 575

This is due to np.array being defaulted at float. If you want to make the array into an integer format, just do this:

foo = np.array([1, 3, 5, 7])
bar = foo.astype(int)

Upvotes: 3

polwel
polwel

Reputation: 647

By default numpy arrays only store data of a single type. Since initially it contains a floating point number (10.5), the entire array is floating point.

Instead of testing the data type, you need to test the value, e.g. by grades[i].is_integer().

Upvotes: 5

Related Questions