How can I check for a string in a list of tuples and only output once if not found?












1















I have a list of tuples, holding information about people (one for each tuple, with things like (name, age, etc.)). I want to check the list to see whether any names match a user input. My problem is if I use a for loop I then get multiple lines returning false, rather than just one. I also cannot then ask the user to try again, until success. My current code is:



last_name = input("Please input person's last name")

for person in personList:
if person[0] == last_name.capitalize():
print("success")
else:
print("fail")


This will print out "fail" for each player, rather than just once, and will not prompt a user to try again. I know a while loop would enable multiple attempts but I can't see how to link the while with the for, and still output a "fail" only once.



As I'm trying to learn more about tuples, please don't suggest using objects. I know it would make a lot more sense but it doesn't help me understand tuples.










share|improve this question





























    1















    I have a list of tuples, holding information about people (one for each tuple, with things like (name, age, etc.)). I want to check the list to see whether any names match a user input. My problem is if I use a for loop I then get multiple lines returning false, rather than just one. I also cannot then ask the user to try again, until success. My current code is:



    last_name = input("Please input person's last name")

    for person in personList:
    if person[0] == last_name.capitalize():
    print("success")
    else:
    print("fail")


    This will print out "fail" for each player, rather than just once, and will not prompt a user to try again. I know a while loop would enable multiple attempts but I can't see how to link the while with the for, and still output a "fail" only once.



    As I'm trying to learn more about tuples, please don't suggest using objects. I know it would make a lot more sense but it doesn't help me understand tuples.










    share|improve this question



























      1












      1








      1








      I have a list of tuples, holding information about people (one for each tuple, with things like (name, age, etc.)). I want to check the list to see whether any names match a user input. My problem is if I use a for loop I then get multiple lines returning false, rather than just one. I also cannot then ask the user to try again, until success. My current code is:



      last_name = input("Please input person's last name")

      for person in personList:
      if person[0] == last_name.capitalize():
      print("success")
      else:
      print("fail")


      This will print out "fail" for each player, rather than just once, and will not prompt a user to try again. I know a while loop would enable multiple attempts but I can't see how to link the while with the for, and still output a "fail" only once.



      As I'm trying to learn more about tuples, please don't suggest using objects. I know it would make a lot more sense but it doesn't help me understand tuples.










      share|improve this question
















      I have a list of tuples, holding information about people (one for each tuple, with things like (name, age, etc.)). I want to check the list to see whether any names match a user input. My problem is if I use a for loop I then get multiple lines returning false, rather than just one. I also cannot then ask the user to try again, until success. My current code is:



      last_name = input("Please input person's last name")

      for person in personList:
      if person[0] == last_name.capitalize():
      print("success")
      else:
      print("fail")


      This will print out "fail" for each player, rather than just once, and will not prompt a user to try again. I know a while loop would enable multiple attempts but I can't see how to link the while with the for, and still output a "fail" only once.



      As I'm trying to learn more about tuples, please don't suggest using objects. I know it would make a lot more sense but it doesn't help me understand tuples.







      python list tuples






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 23 '18 at 17:20









      usr2564301

      17.8k73370




      17.8k73370










      asked Nov 23 '18 at 17:09









      LukeLuke

      185




      185
























          3 Answers
          3






          active

          oldest

          votes


















          2














          You need two modifications: a way to stop the loop if you find a match, and a way to print 'fail' only if you found no matches in the entire list.



          You can get the first modification by adding a break in the if statement, and you can get the second one by adding an else clause to the for loop, which means "run this code if the loop ran to its full completion".



          for person in personList:
          if person[0] == last_name.capitalize():
          print("success")
          break
          else:
          print("fail")





          share|improve this answer

































            0














            You could simplify checking if user input value is in personList to one line like so and then check whether input matched at least once and if it did print 'success' and break loop, else print 'fail' and ask user again.



            personList = [('Abc', 'Cba'), ('Xyz', 'Zyx')]

            while True:
            last_name = input("Please input person's last name: ").capitalize()

            if any(last_name == i[0] for i in personList):
            print("success")
            break
            else:
            print("fail")


            Output:



            Please input person's last name: random
            fail
            Please input person's last name: xyz
            success





            share|improve this answer































              0














              So first of all lets understand whats happening.
              For each person in the tuple you ask if his name is X.



              So accordingly each person will answer you: "No", until you get to the right person, and only that person will say: "Yes", and even further, unless he is the last one it will go on until the very end.



              In conclusion, you're asking every single tuple to say whether it matches the user input, or not.



              But there is also an easy way of fixing this. So what can we do instead?



              We will just collect every answer, and then check whether our input exists in the collection.



              Lets write down in code:



              total_collection = 
              for person in personList:
              if person[0] == last_name.capitalize():
              total_collection.append("1")
              else:
              total_collection.append("0")
              if "1" in total_collection:
              print("Success!")
              else:
              print("Fail...")


              In this code, the string "1" represents a match, and the string "0" represents no-match.
              Also, this way you can say at which index the match/es was/were located.






              share|improve this answer























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53450640%2fhow-can-i-check-for-a-string-in-a-list-of-tuples-and-only-output-once-if-not-fou%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                2














                You need two modifications: a way to stop the loop if you find a match, and a way to print 'fail' only if you found no matches in the entire list.



                You can get the first modification by adding a break in the if statement, and you can get the second one by adding an else clause to the for loop, which means "run this code if the loop ran to its full completion".



                for person in personList:
                if person[0] == last_name.capitalize():
                print("success")
                break
                else:
                print("fail")





                share|improve this answer






























                  2














                  You need two modifications: a way to stop the loop if you find a match, and a way to print 'fail' only if you found no matches in the entire list.



                  You can get the first modification by adding a break in the if statement, and you can get the second one by adding an else clause to the for loop, which means "run this code if the loop ran to its full completion".



                  for person in personList:
                  if person[0] == last_name.capitalize():
                  print("success")
                  break
                  else:
                  print("fail")





                  share|improve this answer




























                    2












                    2








                    2







                    You need two modifications: a way to stop the loop if you find a match, and a way to print 'fail' only if you found no matches in the entire list.



                    You can get the first modification by adding a break in the if statement, and you can get the second one by adding an else clause to the for loop, which means "run this code if the loop ran to its full completion".



                    for person in personList:
                    if person[0] == last_name.capitalize():
                    print("success")
                    break
                    else:
                    print("fail")





                    share|improve this answer















                    You need two modifications: a way to stop the loop if you find a match, and a way to print 'fail' only if you found no matches in the entire list.



                    You can get the first modification by adding a break in the if statement, and you can get the second one by adding an else clause to the for loop, which means "run this code if the loop ran to its full completion".



                    for person in personList:
                    if person[0] == last_name.capitalize():
                    print("success")
                    break
                    else:
                    print("fail")






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 23 '18 at 19:45

























                    answered Nov 23 '18 at 17:18









                    John GordonJohn Gordon

                    9,76151729




                    9,76151729

























                        0














                        You could simplify checking if user input value is in personList to one line like so and then check whether input matched at least once and if it did print 'success' and break loop, else print 'fail' and ask user again.



                        personList = [('Abc', 'Cba'), ('Xyz', 'Zyx')]

                        while True:
                        last_name = input("Please input person's last name: ").capitalize()

                        if any(last_name == i[0] for i in personList):
                        print("success")
                        break
                        else:
                        print("fail")


                        Output:



                        Please input person's last name: random
                        fail
                        Please input person's last name: xyz
                        success





                        share|improve this answer




























                          0














                          You could simplify checking if user input value is in personList to one line like so and then check whether input matched at least once and if it did print 'success' and break loop, else print 'fail' and ask user again.



                          personList = [('Abc', 'Cba'), ('Xyz', 'Zyx')]

                          while True:
                          last_name = input("Please input person's last name: ").capitalize()

                          if any(last_name == i[0] for i in personList):
                          print("success")
                          break
                          else:
                          print("fail")


                          Output:



                          Please input person's last name: random
                          fail
                          Please input person's last name: xyz
                          success





                          share|improve this answer


























                            0












                            0








                            0







                            You could simplify checking if user input value is in personList to one line like so and then check whether input matched at least once and if it did print 'success' and break loop, else print 'fail' and ask user again.



                            personList = [('Abc', 'Cba'), ('Xyz', 'Zyx')]

                            while True:
                            last_name = input("Please input person's last name: ").capitalize()

                            if any(last_name == i[0] for i in personList):
                            print("success")
                            break
                            else:
                            print("fail")


                            Output:



                            Please input person's last name: random
                            fail
                            Please input person's last name: xyz
                            success





                            share|improve this answer













                            You could simplify checking if user input value is in personList to one line like so and then check whether input matched at least once and if it did print 'success' and break loop, else print 'fail' and ask user again.



                            personList = [('Abc', 'Cba'), ('Xyz', 'Zyx')]

                            while True:
                            last_name = input("Please input person's last name: ").capitalize()

                            if any(last_name == i[0] for i in personList):
                            print("success")
                            break
                            else:
                            print("fail")


                            Output:



                            Please input person's last name: random
                            fail
                            Please input person's last name: xyz
                            success






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 23 '18 at 17:15









                            Filip MłynarskiFilip Młynarski

                            1,7711413




                            1,7711413























                                0














                                So first of all lets understand whats happening.
                                For each person in the tuple you ask if his name is X.



                                So accordingly each person will answer you: "No", until you get to the right person, and only that person will say: "Yes", and even further, unless he is the last one it will go on until the very end.



                                In conclusion, you're asking every single tuple to say whether it matches the user input, or not.



                                But there is also an easy way of fixing this. So what can we do instead?



                                We will just collect every answer, and then check whether our input exists in the collection.



                                Lets write down in code:



                                total_collection = 
                                for person in personList:
                                if person[0] == last_name.capitalize():
                                total_collection.append("1")
                                else:
                                total_collection.append("0")
                                if "1" in total_collection:
                                print("Success!")
                                else:
                                print("Fail...")


                                In this code, the string "1" represents a match, and the string "0" represents no-match.
                                Also, this way you can say at which index the match/es was/were located.






                                share|improve this answer




























                                  0














                                  So first of all lets understand whats happening.
                                  For each person in the tuple you ask if his name is X.



                                  So accordingly each person will answer you: "No", until you get to the right person, and only that person will say: "Yes", and even further, unless he is the last one it will go on until the very end.



                                  In conclusion, you're asking every single tuple to say whether it matches the user input, or not.



                                  But there is also an easy way of fixing this. So what can we do instead?



                                  We will just collect every answer, and then check whether our input exists in the collection.



                                  Lets write down in code:



                                  total_collection = 
                                  for person in personList:
                                  if person[0] == last_name.capitalize():
                                  total_collection.append("1")
                                  else:
                                  total_collection.append("0")
                                  if "1" in total_collection:
                                  print("Success!")
                                  else:
                                  print("Fail...")


                                  In this code, the string "1" represents a match, and the string "0" represents no-match.
                                  Also, this way you can say at which index the match/es was/were located.






                                  share|improve this answer


























                                    0












                                    0








                                    0







                                    So first of all lets understand whats happening.
                                    For each person in the tuple you ask if his name is X.



                                    So accordingly each person will answer you: "No", until you get to the right person, and only that person will say: "Yes", and even further, unless he is the last one it will go on until the very end.



                                    In conclusion, you're asking every single tuple to say whether it matches the user input, or not.



                                    But there is also an easy way of fixing this. So what can we do instead?



                                    We will just collect every answer, and then check whether our input exists in the collection.



                                    Lets write down in code:



                                    total_collection = 
                                    for person in personList:
                                    if person[0] == last_name.capitalize():
                                    total_collection.append("1")
                                    else:
                                    total_collection.append("0")
                                    if "1" in total_collection:
                                    print("Success!")
                                    else:
                                    print("Fail...")


                                    In this code, the string "1" represents a match, and the string "0" represents no-match.
                                    Also, this way you can say at which index the match/es was/were located.






                                    share|improve this answer













                                    So first of all lets understand whats happening.
                                    For each person in the tuple you ask if his name is X.



                                    So accordingly each person will answer you: "No", until you get to the right person, and only that person will say: "Yes", and even further, unless he is the last one it will go on until the very end.



                                    In conclusion, you're asking every single tuple to say whether it matches the user input, or not.



                                    But there is also an easy way of fixing this. So what can we do instead?



                                    We will just collect every answer, and then check whether our input exists in the collection.



                                    Lets write down in code:



                                    total_collection = 
                                    for person in personList:
                                    if person[0] == last_name.capitalize():
                                    total_collection.append("1")
                                    else:
                                    total_collection.append("0")
                                    if "1" in total_collection:
                                    print("Success!")
                                    else:
                                    print("Fail...")


                                    In this code, the string "1" represents a match, and the string "0" represents no-match.
                                    Also, this way you can say at which index the match/es was/were located.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Nov 23 '18 at 17:23









                                    Emanuel LEmanuel L

                                    658




                                    658






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53450640%2fhow-can-i-check-for-a-string-in-a-list-of-tuples-and-only-output-once-if-not-fou%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        404 Error Contact Form 7 ajax form submitting

                                        How to know if a Active Directory user can login interactively

                                        TypeError: fit_transform() missing 1 required positional argument: 'X'