-2
a = []

for i in range (5):
    a.append(input ("Enter only one character: "))
a.sort()
print(a)

a.reverse()
print(a)

This is my code and I don't know how to detect a single character. If a user input two character they will get an error but if the user input single character the input item will be in the list.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Tomerikoo Feb 04 '21 at 14:35
  • You could have a check for how long the input is from the user? – dfundako Feb 04 '21 at 14:35
  • Save the input to a variable and check its [`len()`](https://docs.python.org/3/library/functions.html#len)? – Tomerikoo Feb 04 '21 at 14:36
  • Are you asking how to determine the length of a string? Did you read https://docs.python.org/3/tutorial/introduction.html#strings already? – mkrieger1 Feb 04 '21 at 14:36

3 Answers3

0

Assuming that the OP wants to have a list filled with n valid entries, one solution would be:

a = []
for n in range(5):
    while True:
        answer = input("Enter only one character: ")
        if len(answer) == 1:
            a.append(answer)
            break
        print('I said ONLY ONE character!')

The while True loop will be broken if a valid answer is given, otherwise it will print a reminder to the user and ask for new input. Unless the user is going to give the wrong answer infinite times, this code will ensure the creation of a list with n valid items in it.

alec_djinn
  • 10,104
  • 8
  • 46
  • 71
  • The while loop makes the for loop unnecessary. It is not possible anymore to limit the number of times the user is asked for an input. – Semmel Feb 04 '21 at 14:43
  • 1
    @Semmel why? The `while` loop is to make sure the user inputs a single character. The `for` loop is to make sure a total of 5 ***valid*** inputs were given... – Tomerikoo Feb 04 '21 at 14:50
  • @Semmel I think the OP wants 5 items in the list eventually. – alec_djinn Feb 04 '21 at 14:57
0

You can just check if the length of the string equals to one.

a = []

for i in range(5):
    txt = input('Enter only one character: ')
    if len(txt) == 1: #Checking if length is one
        a.append(txt)
a.sort()
print(a)
a.reverse()
print(a)
ph140
  • 478
  • 3
  • 10
-1
a = []

for i in range (5):
    c = input ("Enter only one character: ")
    if len(c) == 1:
        a.append(c)
    else:
        raise ValueError("Input is not a single character")
a.sort()
print(a)

a.reverse()
print(a)
Semmel
  • 575
  • 2
  • 8
  • Raising an exception like that will simply break the execution of the code, the program will crash and the user will not be able to enter a new input. – alec_djinn Feb 04 '21 at 14:59
  • that seems what was asked for since that is what an error is. – Semmel Feb 04 '21 at 17:29