Prompting the user again and again for a single character

To accept only a single character from the user input:

  • Run a while loop to iterate until and unless the user inputs a single character.
  • If the user inputs a single character, then break out of the loop.
  • Else the user gets prompted again and again.

Python3




usrInput = ''
 
while True:
    usrInput = input("Enter a single character as input: ")
    if len(usrInput) == 1:
        print(f'Your single character input was: {usrInput}')
        break
    print("Please enter a single character to continue\n")


Output:

Enter only a single character: adsf
Please enter a single character to continue

Enter only a single character: 2345
Please enter a single character to continue

Enter only a single character: 
Please enter a single character to continue

Enter only a single character: a
Your single character input was: a

The time complexity is O(1),  because the loop will execute only once for valid input, which consists of a single character.

The auxiliary space complexity of this code is constant O(1), because it only uses a fixed amount of memory to store the input character and the output message.

This program kept running until the user enter only a single character as input. If the user inputs a single character it prints the character and breaks out of the loop and the program finishes.

How to Take Only a Single Character as an Input in Python

Through this article, you will learn how to accept only one character as input from the user in Python.

Similar Reads

Prompting the user again and again for a single character

To accept only a single character from the user input:...

Using only one character from the user input string

...