0

I need help encasing the:

if any(c.isdigit() for c in name):
print("Not a valid name!")

inside of a while statement. This pretty much just reads the input for the "name" variable and sees if there's an integer in it. How could I use that in a while statement? I just want it to be if the user inputs a variable into the input, it will print out the string up above and loop back and ask the user for their name again until they successfully enter in a string with no integer, then I want it to break. Any help?

print("Hello there!")
yn = None
while yn != "y":
    print("What is your name?")
    name = raw_input()
    if any(c.isdigit() for c in name):
        print("Not a valid name!")
    print("Oh, so your name is {0}? Cool!".format(name))
    print("Now how old are you?")
    age = raw_input()
    print("So your name is {0} and you're {1} years old?".format(name, age))
    print("y/n?")
    yn = raw_input()
    if yn == "y":
        break
    if yn == "n":
        print("Then here, try again!")
print("Cool!")

3 Answers 3

1

Use while True and a break to end the loop when a valid name has been entered:

while True:
    name = raw_input("What is your name? ")
    if not any(c.isdigit() for c in name):
        break
    print("Not a valid name!")

This is much easier than first initializing name to something that is invalid then using the any() expression in the while test.

Sign up to request clarification or add additional context in comments.

Comments

0

Something like this:

name = input("What is your name? : ")
while any(c.isdigit() for c in name): 
    print ("{0} is invalid, Try again".format(name))
    name = input("What is your name? : ")

demo:

What is your name? : foo1
foo1 is invalid, Try again
What is your name? : 10bar
10bar is invalid, Try again
What is your name? : qwerty

Comments

0

Are you just saying you want a continue after your print("Not a valid name!")?

print("Hello there!")
yn = None
while yn != "y":
    print("What is your name?")
    name = raw_input()
    if any(c.isdigit() for c in name):
        print("Not a valid name!")
        continue
    print("Oh, so your name is {0}? Cool!".format(name))
    ...

The continue will just go back to the top of your loop.

2 Comments

Yes, I want it to keep looping until the user enters a valid name (One with no integers)
So ... isn't this the answer to your question, then?

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.