0

My current code searches through a list of tuples and it will print the entries that match the entered string. If it cannot find the string it will print an error. However my code prints the error even after printing the results found.

            if scheme not in i:
                    print("Could not find a record with degree scheme",scheme)

How would i change this so it will find all the entries of the for loop, and if none are found it shows the error. Because currently it shows the entries found then also the "Could not find.." error.

  • Wrap the second part of your code in an else statement either after the for loop or after the if statement. – Christian Dean Dec 07 '16 at 16:07
  • so i could technically make it an elif statement? Do you mean the first If statement or the second if statement? –  Dec 07 '16 at 16:08

2 Answers2

1

You can use a flag

if choice == 1:
        found_flag = False
        scheme=input("Enter the degree scheme: ").upper()
        for i in lst:
            if i[2] == scheme:
                printStud(i[0:5])
                found_flag = True

        if not found_flag:
                print("Could not find a record with degree scheme",scheme)
Yuval Atzmon
  • 5,645
  • 3
  • 41
  • 74
  • If the `found flag` is set to True, and i use the found flag inside another for/if statement outside this current one, will the found flag value be reset to false again or stay as true? –  Dec 07 '16 at 16:13
  • 1
    It probably makes more sense scope-wise to bring the flag inside the outer `if`. – Iluvatar Dec 07 '16 at 16:14
  • @godlypython, you would have to reset the value to False. See http://stackoverflow.com/questions/291978/short-description-of-scoping-rules, for variable scoping rules in python – Yuval Atzmon Dec 07 '16 at 16:17
  • yes i brought the flag to the complete start of my while loop ( you cant see this code); does that mean flag is set to false if its outside? Or do i still need to reset –  Dec 07 '16 at 16:18
  • @godlypython, you have to explicitly set its value – Yuval Atzmon Dec 07 '16 at 16:20
0

scheme is never in i, as you use i to cycle through the tuples in lst, and as such it is a single tuple from lst. Try

if scheme not in [s[2] for s in lst]:
Iluvatar
  • 1,537
  • 12
  • 13