Search code examples
pythonloopsbreakrestrictisalpha

How can you restrict user to only input alphabets in Python?


I am a beginner trying to learn Python. First question.

Trying to find a way to ask users to input alphabets only. Wrote this but it doesn't work! It returns True and then skips the rest before continuing to the else clause. break doesn't work either.

Can someone point out why? I assume it's very elementary, but I'm stuck and would appreciate it if someone could pull me out.

while True:
    n = input("write something")
    if print(n.isalpha()) == True:
        print(n)
        break
    else:
        print("Has to be in alphabets only.")

Solution

  • I've fixed the bug, below is the updated code:

    while True:
        n = input("write something: ")
        if n.isalpha() == True:
            print(n)
            break
        else:
            print("Has to be in alphabets only.")