CoreVisional
CoreVisional

Reputation: 99

Check for int and float given by the user input in a list

How do I check the data type provided by the user input in a list specifically?

For example:

user_inp = [float(number) for number in input(
"Enter Number: ").replace(',', ' ').split()]

>>> print(user_inp) 
Enter Number: 1 2 3 4 
[1.0, 2.0, 3.0, 4.0]

I want to specifically check if the user has included decimals in the input. If they gave 1.0 or 2.0 specifically, then I want the program to accept that, and if they gave integers, then the program should accept integers. The reason why I use float is that using int will trigger an error and also the user can input whatever numbers they'd like without crashing the program.

Desired Result:

>>> print(user_inp)
Enter Number: 1 2 3 4
[1, 2, 3, 4]

>>> print(user_inp)
Enter Number: 1.0 2.0 3.0 4.0
[1.0, 2.0, 3.0, 4.0]

What I have tried:

lst = []

for num in user_inp:
    if isinstance(num, float):
        lst.append(int(num))

print(lst)

# input: 1.0 2.0
# output: [1, 2]

Upvotes: 1

Views: 691

Answers (2)

ThePyGuy
ThePyGuy

Reputation: 18426

You don't need to manually check for the type, if you use ast.literal_eval, the type will be preserved based on string representation, that being said, value entered with float representation will be stored as float and integer representation will be stored as integer, else will be stored as string:

import ast
user_inp = [ast.literal_eval(number) for number in input(
"Enter Number: ").replace(',', ' ').split()]

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71580

Try checking for the decimal point:

>>> user_inp = [float(number) if '.' in number else int(number) for number in input("Enter Number: ").replace(',', ' ').split()]
Enter Number: 1.0 2 3.0 4
>>> user_inp
[1.0, 2, 3.0, 4]
>>> 

Upvotes: 1

Related Questions