简体   繁体   中英

I need my code to only accept float values

def check_datatype (data,datatype,message):


        if datatype == "Float":
            if not data:
                if not data:
                    print(message)
                return False,data
            else:
                return True,data


check = False
while not check:
    some_text = input('Input a float: ')
    check,a_float = check_datatype(some_text,"Float","You must input a number")
print(a_float)

I've tried using .isdecimal but it is not working (If not data.isdecimal ) This second part of the code is correct but the first part is wrong somehow.

You can use .isinstance() to get True of False if the value is defined type.

value = 5

print(isinstance(value, float))

# Returns False

In your if statement:

if isinstance(value, float):
    print(value, "is float")
elif isinstance(value, int):
    print(value, "is interger")

I suggest using if isinstance(datatype,float): instead of if datatype == "Float":

As other users suggested, isinstance is very helpful in these situations.

Your code should look like this:

def funct(data: float) -> (bool, float):
    isFloat = False
    if isinstance(data, float):
        isFloat = True
    else:
        print("message")
    return (isFloat, data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM