1

I want to check if there is an element in a list of array for example, I have:

horselist = [(1,"horse A","owner of A"), (2,"horse B", "owner of B")]

So if I want to check if "horse A" is in the list. I tried:

horsename_check = input("Enter horse name: ")
for i in horselist:
    if (i[1] == horsename_check):
        treatment = input("Enter treatment: ")

        print("{0} found with treatment {1}".format(horsename_check,treatment))

    else:
        print("{0} id {1} profile is not in the database. "
              "(You must enter the horse's profile before adding med records)".format(horsename_check, i[0]))

But if I input the horse name is : "horse B". Input will also check every array in the list and print out the statement not found in array 1.

input:
Enter the horse name:horse B
horse B id 2 profile is not in the database. (You must enter the horse's profile before adding med records)
Enter treatment: 

So how can I get rid of that ? Thank you.

Python learner
  • 1,159
  • 1
  • 8
  • 20

3 Answers3

3

You just need to move the else to be part of the for loop:

horsename_check = input("Enter horse name: ")
for i in horselist:
    if (i[1] == horsename_check):
        treatment = input("Enter treatment: ")
        print("{0} found with treatment {1}".format(horsename_check, treatment))
        break
else:
    print("{0} id {1} profile is not in the database. "
          "(You must enter the horse's profile before adding med records)".format(horsename_check, i[0]))
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
2

You need to print the "horse not found" message only after traversing all the list, not very time you find an element. And you should exit the loop after finding the correct horse, no point in iterating beyond that point. You should use for's else construct for this:

horsename_check = input("Enter horse name: ")
for i in horselist:
    if i[1] == horsename_check:
        treatment = input("Enter treatment: ")
        print("{0} found with treatment {1}".format(horsename_check,treatment))
        break
else:
    print("{0} id {1} profile is not in the database. "
          "(You must enter the horse's profile before adding med records)".format(horsename_check, i[0]))
Óscar López
  • 232,561
  • 37
  • 312
  • 386
-1
horselist = [(1,"horse A","owner of A"), (2,"horse B", "owner of B")]
neededHorse = "horse B"
found = 0
for horse in horselist:
    if neededHorse in horse:
        found = horse[0]
if found != 0:
    print("Horse found in ",found)
else:
    print("Horse not found!")

This should work, you can keep a condition outside the loop and check it post the loop

Zaid Al Shattle
  • 1,454
  • 1
  • 12
  • 21