Only accept a single character from user Input in Python

avatar

Borislav Hadzhiev

Last updated: Aug 26, 2022

banner

Photo from Unsplash

Only accept a single character from user Input in Python #

To only accept a single character from user input:

  1. Use a while loop to iterate until the user enters a single character.
  2. If the user enters a single character, use the break statement to break out of the loop.
  3. If the condition is not met, prompt the user again.
main.py
user_input = '' while True: user_input = input('Enter a single character: ') if len(user_input) == 1: print(user_input) break else: print('Enter a single character to continue.') continue # 👇️ if you need to convert the character to lower or uppercase print(user_input.lower()) print(user_input.upper())

input only accept one character

We used a while loop to iterate until the user enters a single character.

The if statement uses the len() function to check if the user entered a single character.

The len() function returns the length (the number of items) of an object.

main.py
print(len('a')) # 👉️ 1 print(len('ab')) # 👉️ 2
The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

If the user entered a single character, we use the break statement to exit out of the loop.

main.py
user_input = '' while True: user_input = input('Enter a single character: ') if len(user_input) == 1: print(user_input) break else: print('Enter a single character to continue.') continue

The break statement breaks out of the innermost enclosing for or while loop.

If the user enters zero or more than 1 character, we prompt them again.

The continue statement continues with the next iteration of the loop.

When validating user input in a while loop, we use the continue statement when the input is invalid.

If the input is valid, we use the break statement to exit out of the while loop.

Use the str.isalpha() method if you only want to allow the user to enter a single letter.

main.py
user_input = '' while True: user_input = input('Enter a single letter: ') if len(user_input) == 1 and user_input.isalpha(): print(user_input) break else: print('Enter a single letter to continue.') continue

input only accept one letter

We used the boolean and operator, so for the if block to run, both conditions have to be met.

The str.isalpha() method returns True if all characters in the string are alphabetic and there is at least one character, otherwise False is returned.

main.py
print('a'.isalpha()) # 👉️ True print('1'.isalpha()) # 👉️ False

If the user enters a single letter, the if block runs and we exit out of the while loop, otherwise, we prompt the user again.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.