0

I'm working on a project that requires the user to input names of players into a list. Is there any way to prevent the same name from being inputted?

Code I have so far:

#Team 1 naming
        print("Team 1 player input")
        elem = int(input("Amount of players: "))
        for i in range(0, elem):
            Team1_list.append(str(input(f'Enter player number {num_team1} name (In batting order) eg J.Smith: ')))
            num_team1 = num_team1 + 1
        print(Team1_list)

I've tried some things but none seem to work

3 Answers3

0

If you want the user to retry the entry, you can use something like this:

print("Team 1 player input")
elem = int(input("Amount of players: "))
for i in range(0, elem):
    p = None
    while not p or p in Team1_list:
        p = input(f'Enter player number {num_team1} name (In batting order) eg J.Smith: ')
        if p in Team1_list: print('That player already entered, please retry...')
    Team1_list.append(p)
    num_team1 = num_team1 + 1
print(Team1_list)
Mike67
  • 11,175
  • 2
  • 7
  • 15
0

If you're using Python 3.6+, you will have the benefit of dict keys are remembering your insert order. So you get benefit of both the list and set at the same. Consider the following:

#Team 1 naming
print("Team 1 player input")
elem = int(input("Amount of players: "))
team = {}
while len(team) < elem:
    num_team1 = len(team)+1
    name = str(input(f'Enter player number {num_team1} name (In batting order) eg J.Smith: ')))
    team[name] = 1
print(list(team.keys()))

If you enter the same name again, your num_team1 will not increment and your "list" will ignore that duplicated entry (i.e. keep only the first in its original order)

adrtam
  • 6,991
  • 2
  • 12
  • 27
0

Use a set with set{}

no_duplicates = {1, 2, 1, 3, 2}
print(no_duplicates)

{1, 2, 3}
sushanth
  • 8,275
  • 3
  • 17
  • 28