I expected that the code would ask me for input as many times as I want and then print out the number of times the input has been entered along with the name, capitalized. However, it only prints out the last input with 1 in front of the input
Can you tell where am I wrong
while True:
try:
lst = [
input('Enter name here: ')
]
except (KeyboardInterrupt):
for n in lst:
print(lst.count(n), n.upper())
You have to append the name taking from the input to the lst
, but instead you are here assigning the lst
to the list of only the newest named enter by the user.
Use lst.append(input(...))
Also, you have one more problem in your code, it is that your code will never end unless you closes the terminal, it is because you are handling the KeyboardInterruput error but you are not actually stopping the while loop, so it will never end. for that you have to add break after the list.
lst = []
while True:
try:
lst.append(input('Enter name here: '))
except KeyboardInterrupt:
print()
for n in set(lst): # use set so that it will not print data for duplicate names
print(lst.count(n), n.upper())
exit()
Enter name here: asd
Enter name here: asd
Enter name here: asd
Enter name here: a
Enter name here: d
Enter name here: qw
Enter name here: a
Enter name here: sd
Enter name here: asd
Enter name here:
1 D
1 QW
1 SD
4 ASD
2 A
Other way, is if you only want loop to run n times the you do that too
n = 10
lst = []
for i in range(n):
lst.append(input('Enter name here: '))
print() # just for one line space
for n in set(lst):
print(lst.count(n), n.upper())