1

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)
1
  • That name will never break the outer while loop because input name is in another scope and the inner loop has nothing that breaks it, because if it gets a ValueError then it passes and runs again. Commented Mar 28, 2020 at 15:21

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.