How to Only Allow Letters when Taking User Input in Python?

Estimated read time 1 min read

In Python, you can use the isalpha() method to check if a string contains only letters. To only allow letters when taking user input, you can use a loop that repeatedly prompts the user to enter a string until a valid input is entered.

Here is an example:

while True:
    user_input = input("Enter a string: ")
    if user_input.isalpha():
        print("Error: Please enter only letters.")

print("You entered:", user_input)

In this example, we use a while loop to repeatedly prompt the user to enter a string. We use the input() function to accept user input and check if it contains only letters using the isalpha() method.

If the input contains only letters, we break out of the loop and print the input using the print() function. If the input contains non-letter characters, we print an error message and continue the loop.

Note that the isalpha() method returns False if the string contains any non-letter characters, including whitespace and punctuation. If you need to allow whitespace or punctuation in the input, you may need to use a different method to validate the input.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply