简体   繁体   中英

How to check if a variable is string or an integer?

I have a question about how to warn user to input 'string' instead of 'integer' but it seems that I cannot iterate the loop if user input is integer and ask again please enter string

Example from here

http://pythontutor.com/visualize.html#mode=edit

catNames = []

while True:

    print("Enter the name of cat " + str(len(catNames) + 1) + ' (Or enter nothing to stop):' )

    while True:

        name = input()

        try:
            name = int(name)

        except ValueError:

            print('please enter string')
            pass    

    if name == '':
        break

    catNames = catNames + [name] # list concatenation

print('The cat names are :')
for i in catNames:
    print(' ' + i)

A possible solution is this:

catNames = []

while True:
    print("Enter the name of cat " + str(len(catNames) + 1) + ' (Or enter nothing to stop):' )
    name = input()
    if name.isalpha():
        catNames = catNames + [name] # list concatenation
    elif name == '':
        break
    else:
        print("Please enter a string")


print('The cat names are :')
for i in catNames:
    print(' ' + i)

One while is sufficent, in case a user enters an integer you could 'reset' the value:

catNames = []

while True:
    print("Enter the name of cat " + str(len(catNames) + 1) + ' (Or enter nothing to stop):' )
    name = input()

    if name.strip() == '':
        # no input
        print("exiting!")
        break

    try:
        name = int(name)
        name = None
        print("Please enter a string")
    except ValueError:
        pass
    finally:
        if name is not None:
            catNames.append(name)


print('The cat names are :')
for i in catNames:
    print(' ' + i)

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