简体   繁体   中英

Python: conditional statement and function definition

I am using conditional statement in a function to ask weather an input is float/string/integer and display certain output if it determine each of the input but the input are all taken as string, how to tell the program to identify each input as string/float/integer?

this is the code below;

def strl(name):
    lname = len(name)
    return lname

name = input('please enter your name: ')
if type(name) == int:
    print("sorry, integars don't have a length")
elif type(name) == float:
    print('sorry, float do not have length ')
else:
    print(strl(name))
    print(type(name))

The purpose is not clear to me. Anyway, maybe you can use something like this:

try:
    float(name)
    print("sorry numbers don't have length")
except:
    print(len(name))
    print(type(name))

The input function in python always returns a string. You can read more about it here .

If you want to check whether or not the string contains a number, you can use the int() function to convert the string to an integer.

All the information that you get to input() function is always string . It could be info like: 123, True, [1,2,3]. All of them will be convert to string automatically. You can use len() function to any string, even if it contains only numbers. You can also use string_name.isdigit() function to check, maybe your string contains only digits.

You can use one try block to try convert string to int if this is not possible use another try block to try convert string to float if this also not possible we know this input is a string and length is printable.

def strl(name):
    lname = len(name)
    return lname

name = input('please enter your name: ')

try:
    int(name)
    print("sorry, integars don't have a length")
except:
    try:
        float(name)
        print('sorry, float do not have length ')
    except:
        print(strl(name))
        print(type(name))

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