Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

python 3.x - How to check if input is float or int?

I want to make a simple converter, to print either hexadecimal number of float or integer. My code is:

number = input("Please input your number...... 
") 
if type(number) == type(2.2):
    print("Entered number is float and it's hexadecimal number is:", float.hex(number)) 
elif type(number) == type(2):
    print("Entered number is, ", number,"and it's hexadecimal number is:", hex(number)) 
else:
    print("you entered an invalid number")

But it is always skipping the first two statements and just print else statements. Can someone please find out the problem ?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

TLDR: Convert your input using ast.literal_eval first.


The return type of input in Python3 is always str. Checking it against type(2.2) (aka float) and type(2) (aka int) thus cannot succeed.

>>> number = input()
3
>>> number, type(number)
('3', <class 'str'>)

The simplest approach is to explicitly ask Python to convert your input. ast.literal_eval allows for save conversion to Python's basic data types. It automatically parses int and float literals to the correct type.

>>> import ast
>>> number = ast.literal_eval(input())
3
>>> number, type(number)
(3, <class 'int'>)

In your original code, apply ast.literal_eval to the user input. Then your type checks can succeed:

import ast

number = ast.literal_eval(input("Please input your number...... 
"))
if type(number) is float:
    print("Entered number is float and it's hexadecimal number is:", float.hex(number)) 
elif type(number) is int:
    print("Entered number is, ", number,"and it's hexadecimal number is:", hex(number)) 
else:
    print("you entered an invalid type")

Eagerly attempting to convert the input also means that your program might receive input that is not valid, as far as the converter is concerned. In this case, instead of getting some value of another type, an exception will be raised. Use try-except to respond to this case:

import ast

try:
    number = ast.literal_eval(input("Please input your number...... 
"))
except Exception as err:
    print("Your input cannot be parsed:", err)
else:
    if type(number) is float:
        print("Entered number is float and it's hexadecimal number is:", float.hex(number)) 
    elif type(number) is int:
        print("Entered number is, ", number, "and it's hexadecimal number is:", hex(number)) 
    else:
        print("you entered an invalid type")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...