0

There is a bit of code that I need to implement for the program I am writing (my first ever code project, not too great with programing yet) and my comparison with a users input and an array is not working. It is meant to check that the users input choice is present in the array and adding the input to a variable, but it keeps printing "Player not on this team, try again".

    while first_bowl == False:
        bowler = input("Who is bowling first?: ")
        if bowler == Team1:
            first_bowl = True
            print('first bowler is {bowler}')
        elif bowler != Team1:
            print("Player not on this team, try again")

Any help would be great!

  • You probably want `bowler in Team1` and `bowler not in Team1`, but you don't actually need an `elif`, just an `else` – Nick Oct 29 '20 at 03:12
  • 1
    Does this answer your question? [Fastest way to check if a value exists in a list](https://stackoverflow.com/questions/7571635/fastest-way-to-check-if-a-value-exists-in-a-list) – Nick Oct 29 '20 at 03:13

3 Answers3

1

Use in operator to check if item is in list:

while first_bowl == False:
  bowler = input("Who is bowling first?: ")
  if bowler in Team1:
    first_bowl = True
    print('first bowler is {bowler}')
  else:
    print("Player not on this team, try again")
Wasif
  • 14,755
  • 3
  • 14
  • 34
1

To check if you an element is present in a list, you can use in.

    while first_bowl == False:
        bowler = input("Who is bowling first?: ")
        if bowler in Team1:
            first_bowl = True
            print('first bowler is {bowler}')
        else:
            print("Player not on this team, try again")
Matt Keane
  • 94
  • 2
0

Do that if you want to find a certain string in your list, let's say you want to check if John is in Team 1:

if 'John' in Team1:
    first_bowl = True
    print('First bowler is {bowler}')

But if you ask the user for an input, he can specify the variable, so it gets put into string and then into the variable "bowler", so as a result you can do:

if bowler in Team1:
    first_bowl = True
    print('First bowler is {bowler}')

Which basically checks if the string variable "bowler" provided by the user is in the list named Team 1.

todovvox
  • 170
  • 10