How to Take Only a Single Character as an Input in Python
Last Updated :
10 Mar, 2023
Through this article, you will learn how to accept only one character as input from the user in Python.
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.
Using only one character from the user input string
This approach will use the string indexing to extract only a single required character from the user input.
Using only the first character of the string:
Python3
usrInput = input ( 'Please enter a character:' )[ 0 ]
print (f 'Your single character input was: {usrInput}' )
|
Output:
Please enter a character:adfs
Your single character input was: a
Using the ith character of the string:
Python3
i = 7
usrInput = input ( 'Please enter a character:' )[i]
print (f 'Your single character input was: {usrInput}' )
|
Output:
Please enter a character:0123456789
Your single character input was: 7
Using the last character of the string:
Python3
usrInput = input ( 'Please enter a character:' )[ - 1 ]
print (f 'Your single character input was: {usrInput}' )
|
Output:
Please enter a character:dfsg
Your single character input was: g
The time complexity of this code is constant, O(1), because the input string has only one character and the indexing operation to retrieve the last character takes constant time.
The space complexity is also constant, O(1), because the only memory used is for the variable usrInput, which stores a single character.
Please Login to comment...