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.
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.
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)
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.