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

607 Views Asked by At

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.")
4

There are 4 best solutions below

2
On BEST ANSWER

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.")
1
On

Your problem here is the print function. print does not return anything, so your if statement is always comparing None to True.

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

Your statement should be if n.isalpha() == True:. print won't return anything and so the value is None. Then, you are comparing None with True

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

Don't use print(n.isaplha()), it will be always True. Remove print() and use only n.isalpha()
Try this:-

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