The while loop is not repeating itself upon throwing garbage values












1















I am trying to run a while loop using the 'not' keyword but when I am doing so, the loop is accepting garbage values as well(for eg. bjskdjb) which is not the condition set for the while/for loop.



When I am running the for loop instead, it is throwing a syntax error.



What are the mistakes I am doing here(both using for loop and while loop) ?



I have tried doing it with for loop and while loop.



def askplayerchoice():
playerchoice = ''
while playerchoice not in ('X' , 'O'):
playerchoice = input('Enter X or O: ')
if playerchoice == 'X':
return ['X' , 'O']
else:
return ['O', 'X']
askplayerchoice()

'''
# Using For loop I am getting a syntax error.

def askplayerchoice():
playerchoice = ''
for playerchoice not in ('X' , 'O'):
playerchoice = input('Enter X or O: ')
if playerchoice == 'X':
return ['X' , 'O']
else:
return ['O', 'X']
askplayerchoice()

'''


I am expecting the code to keep asking the user to enter either 'X' or 'O' until the user enters correct values.










share|improve this question



























    1















    I am trying to run a while loop using the 'not' keyword but when I am doing so, the loop is accepting garbage values as well(for eg. bjskdjb) which is not the condition set for the while/for loop.



    When I am running the for loop instead, it is throwing a syntax error.



    What are the mistakes I am doing here(both using for loop and while loop) ?



    I have tried doing it with for loop and while loop.



    def askplayerchoice():
    playerchoice = ''
    while playerchoice not in ('X' , 'O'):
    playerchoice = input('Enter X or O: ')
    if playerchoice == 'X':
    return ['X' , 'O']
    else:
    return ['O', 'X']
    askplayerchoice()

    '''
    # Using For loop I am getting a syntax error.

    def askplayerchoice():
    playerchoice = ''
    for playerchoice not in ('X' , 'O'):
    playerchoice = input('Enter X or O: ')
    if playerchoice == 'X':
    return ['X' , 'O']
    else:
    return ['O', 'X']
    askplayerchoice()

    '''


    I am expecting the code to keep asking the user to enter either 'X' or 'O' until the user enters correct values.










    share|improve this question

























      1












      1








      1








      I am trying to run a while loop using the 'not' keyword but when I am doing so, the loop is accepting garbage values as well(for eg. bjskdjb) which is not the condition set for the while/for loop.



      When I am running the for loop instead, it is throwing a syntax error.



      What are the mistakes I am doing here(both using for loop and while loop) ?



      I have tried doing it with for loop and while loop.



      def askplayerchoice():
      playerchoice = ''
      while playerchoice not in ('X' , 'O'):
      playerchoice = input('Enter X or O: ')
      if playerchoice == 'X':
      return ['X' , 'O']
      else:
      return ['O', 'X']
      askplayerchoice()

      '''
      # Using For loop I am getting a syntax error.

      def askplayerchoice():
      playerchoice = ''
      for playerchoice not in ('X' , 'O'):
      playerchoice = input('Enter X or O: ')
      if playerchoice == 'X':
      return ['X' , 'O']
      else:
      return ['O', 'X']
      askplayerchoice()

      '''


      I am expecting the code to keep asking the user to enter either 'X' or 'O' until the user enters correct values.










      share|improve this question














      I am trying to run a while loop using the 'not' keyword but when I am doing so, the loop is accepting garbage values as well(for eg. bjskdjb) which is not the condition set for the while/for loop.



      When I am running the for loop instead, it is throwing a syntax error.



      What are the mistakes I am doing here(both using for loop and while loop) ?



      I have tried doing it with for loop and while loop.



      def askplayerchoice():
      playerchoice = ''
      while playerchoice not in ('X' , 'O'):
      playerchoice = input('Enter X or O: ')
      if playerchoice == 'X':
      return ['X' , 'O']
      else:
      return ['O', 'X']
      askplayerchoice()

      '''
      # Using For loop I am getting a syntax error.

      def askplayerchoice():
      playerchoice = ''
      for playerchoice not in ('X' , 'O'):
      playerchoice = input('Enter X or O: ')
      if playerchoice == 'X':
      return ['X' , 'O']
      else:
      return ['O', 'X']
      askplayerchoice()

      '''


      I am expecting the code to keep asking the user to enter either 'X' or 'O' until the user enters correct values.







      python python-3.x






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 1 at 5:46









      Prashant MishraPrashant Mishra

      345




      345
























          5 Answers
          5






          active

          oldest

          votes


















          0














          You are returning from the loop to the function caller in the first pass itself, because you use return inside loop. Hence, whatever is the value other than 'X', ['O', 'X'] is returned.



          def askplayerchoice():
          playerchoice = ''
          while playerchoice not in ('X' , 'O'):
          playerchoice = input('Enter X or O: ')
          if playerchoice == 'X':
          return ['X' , 'O']
          elif playerchoice == 'O':
          return ['O', 'X']

          print(askplayerchoice())


          You can also make use of an infinite loop while True: here, like so:



          def askplayerchoice():
          playerchoice = ''
          while True:
          playerchoice = input('Enter X or O: ')
          if playerchoice == 'X':
          return ['X' , 'O']
          elif playerchoice == 'O':
          return ['O', 'X']

          print(askplayerchoice())





          share|improve this answer


























          • Thanks... Worked for while loop.Can you also tell me why this code is not working with For loop.. def askplayerchoice(): playerchoice = '' for playerchoice not in ('X' , 'O'): playerchoice = input('Enter X or O: ') if playerchoice == 'X': return ['X' , 'O'] else: return ['O', 'X'] askplayerchoice()

            – Prashant Mishra
            Jan 1 at 6:57








          • 1





            @PrashantMishra, for does not work like while. for x in (..,..) will take values from (.., ..) one item at a time in each iteration. Try printing: for x in (1,2): print(x). What you did for .. not in (.., ..) is syntactically wrong.

            – Austin
            Jan 1 at 7:01











          • yes, you are right.. I got it now !! BIG THANK YOU for clearing the confusion. Happy New year 2019 to you ! :)

            – Prashant Mishra
            Jan 1 at 7:04



















          2














          You can add a try catch block and throw an exception when the entered string does not match your desired value. I have updated your code for the same. Below is the snippet :



          def askplayerchoice():
          playerchoice = ''
          while playerchoice.lower() not in ('X' , 'O'):
          try:
          playerchoice = str(input('Enter X or O: '))
          if playerchoice.lower() not in ['x','o']:
          raise ValueError('A very specific bad thing happened.')
          if playerchoice.lower() == 'x':
          return ['X' , 'O']
          else:
          return ['O', 'X']
          except ValueError:
          playerchoice = ''


          askplayerchoice()





          share|improve this answer































            0














            Your function is returning a value within the while loop, regardless of what the user input is, and that's causing the loop to end. You need to change your else condition to else if:



            if playerchoice == 'X':
            return ['X' , 'O']
            elif playerchoice == 'O':
            return ['O', 'X']





            share|improve this answer
























            • Thanks.. What is wrong in this condition: for playerchoice not in ('X' , 'O'): playerchoice = input('Enter X or O: ')

              – Prashant Mishra
              Jan 1 at 7:02



















            0














            First you were initializing playerchoice = '' but inside the loop you were only checking for playerchoice == 'X'. But you didn't check for playerchoice == 'O'. therefore it went to the else and got out of the loop.



            This should do the work:



            def askplayerchoice():
            playerchoice = input('Enter X or O: ')
            while playerchoice not in('X', 'O'):
            playerchoice = input('Enter X or O: ')
            if playerchoice == 'X':
            return ['X', 'O']
            elif playerchoice == 'O':
            return ['O', 'X']
            askplayerchoice()





            share|improve this answer

































              0














              When you use return, the while loop will be stopped.
              Try this code, it will keep asking.



              def askplayerchoice():
              playerchoice = ''
              while playerchoice not in ('X' , 'O'):
              playerchoice = input('Enter X or O: ')
              if playerchoice == 'X':
              print('X' , 'O')
              else:
              print('O', 'X')
              return askplayerchoice()
              askplayerchoice()





              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%2f53993274%2fthe-while-loop-is-not-repeating-itself-upon-throwing-garbage-values%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                5 Answers
                5






                active

                oldest

                votes








                5 Answers
                5






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                0














                You are returning from the loop to the function caller in the first pass itself, because you use return inside loop. Hence, whatever is the value other than 'X', ['O', 'X'] is returned.



                def askplayerchoice():
                playerchoice = ''
                while playerchoice not in ('X' , 'O'):
                playerchoice = input('Enter X or O: ')
                if playerchoice == 'X':
                return ['X' , 'O']
                elif playerchoice == 'O':
                return ['O', 'X']

                print(askplayerchoice())


                You can also make use of an infinite loop while True: here, like so:



                def askplayerchoice():
                playerchoice = ''
                while True:
                playerchoice = input('Enter X or O: ')
                if playerchoice == 'X':
                return ['X' , 'O']
                elif playerchoice == 'O':
                return ['O', 'X']

                print(askplayerchoice())





                share|improve this answer


























                • Thanks... Worked for while loop.Can you also tell me why this code is not working with For loop.. def askplayerchoice(): playerchoice = '' for playerchoice not in ('X' , 'O'): playerchoice = input('Enter X or O: ') if playerchoice == 'X': return ['X' , 'O'] else: return ['O', 'X'] askplayerchoice()

                  – Prashant Mishra
                  Jan 1 at 6:57








                • 1





                  @PrashantMishra, for does not work like while. for x in (..,..) will take values from (.., ..) one item at a time in each iteration. Try printing: for x in (1,2): print(x). What you did for .. not in (.., ..) is syntactically wrong.

                  – Austin
                  Jan 1 at 7:01











                • yes, you are right.. I got it now !! BIG THANK YOU for clearing the confusion. Happy New year 2019 to you ! :)

                  – Prashant Mishra
                  Jan 1 at 7:04
















                0














                You are returning from the loop to the function caller in the first pass itself, because you use return inside loop. Hence, whatever is the value other than 'X', ['O', 'X'] is returned.



                def askplayerchoice():
                playerchoice = ''
                while playerchoice not in ('X' , 'O'):
                playerchoice = input('Enter X or O: ')
                if playerchoice == 'X':
                return ['X' , 'O']
                elif playerchoice == 'O':
                return ['O', 'X']

                print(askplayerchoice())


                You can also make use of an infinite loop while True: here, like so:



                def askplayerchoice():
                playerchoice = ''
                while True:
                playerchoice = input('Enter X or O: ')
                if playerchoice == 'X':
                return ['X' , 'O']
                elif playerchoice == 'O':
                return ['O', 'X']

                print(askplayerchoice())





                share|improve this answer


























                • Thanks... Worked for while loop.Can you also tell me why this code is not working with For loop.. def askplayerchoice(): playerchoice = '' for playerchoice not in ('X' , 'O'): playerchoice = input('Enter X or O: ') if playerchoice == 'X': return ['X' , 'O'] else: return ['O', 'X'] askplayerchoice()

                  – Prashant Mishra
                  Jan 1 at 6:57








                • 1





                  @PrashantMishra, for does not work like while. for x in (..,..) will take values from (.., ..) one item at a time in each iteration. Try printing: for x in (1,2): print(x). What you did for .. not in (.., ..) is syntactically wrong.

                  – Austin
                  Jan 1 at 7:01











                • yes, you are right.. I got it now !! BIG THANK YOU for clearing the confusion. Happy New year 2019 to you ! :)

                  – Prashant Mishra
                  Jan 1 at 7:04














                0












                0








                0







                You are returning from the loop to the function caller in the first pass itself, because you use return inside loop. Hence, whatever is the value other than 'X', ['O', 'X'] is returned.



                def askplayerchoice():
                playerchoice = ''
                while playerchoice not in ('X' , 'O'):
                playerchoice = input('Enter X or O: ')
                if playerchoice == 'X':
                return ['X' , 'O']
                elif playerchoice == 'O':
                return ['O', 'X']

                print(askplayerchoice())


                You can also make use of an infinite loop while True: here, like so:



                def askplayerchoice():
                playerchoice = ''
                while True:
                playerchoice = input('Enter X or O: ')
                if playerchoice == 'X':
                return ['X' , 'O']
                elif playerchoice == 'O':
                return ['O', 'X']

                print(askplayerchoice())





                share|improve this answer















                You are returning from the loop to the function caller in the first pass itself, because you use return inside loop. Hence, whatever is the value other than 'X', ['O', 'X'] is returned.



                def askplayerchoice():
                playerchoice = ''
                while playerchoice not in ('X' , 'O'):
                playerchoice = input('Enter X or O: ')
                if playerchoice == 'X':
                return ['X' , 'O']
                elif playerchoice == 'O':
                return ['O', 'X']

                print(askplayerchoice())


                You can also make use of an infinite loop while True: here, like so:



                def askplayerchoice():
                playerchoice = ''
                while True:
                playerchoice = input('Enter X or O: ')
                if playerchoice == 'X':
                return ['X' , 'O']
                elif playerchoice == 'O':
                return ['O', 'X']

                print(askplayerchoice())






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 1 at 7:05

























                answered Jan 1 at 5:50









                AustinAustin

                11.3k3829




                11.3k3829













                • Thanks... Worked for while loop.Can you also tell me why this code is not working with For loop.. def askplayerchoice(): playerchoice = '' for playerchoice not in ('X' , 'O'): playerchoice = input('Enter X or O: ') if playerchoice == 'X': return ['X' , 'O'] else: return ['O', 'X'] askplayerchoice()

                  – Prashant Mishra
                  Jan 1 at 6:57








                • 1





                  @PrashantMishra, for does not work like while. for x in (..,..) will take values from (.., ..) one item at a time in each iteration. Try printing: for x in (1,2): print(x). What you did for .. not in (.., ..) is syntactically wrong.

                  – Austin
                  Jan 1 at 7:01











                • yes, you are right.. I got it now !! BIG THANK YOU for clearing the confusion. Happy New year 2019 to you ! :)

                  – Prashant Mishra
                  Jan 1 at 7:04



















                • Thanks... Worked for while loop.Can you also tell me why this code is not working with For loop.. def askplayerchoice(): playerchoice = '' for playerchoice not in ('X' , 'O'): playerchoice = input('Enter X or O: ') if playerchoice == 'X': return ['X' , 'O'] else: return ['O', 'X'] askplayerchoice()

                  – Prashant Mishra
                  Jan 1 at 6:57








                • 1





                  @PrashantMishra, for does not work like while. for x in (..,..) will take values from (.., ..) one item at a time in each iteration. Try printing: for x in (1,2): print(x). What you did for .. not in (.., ..) is syntactically wrong.

                  – Austin
                  Jan 1 at 7:01











                • yes, you are right.. I got it now !! BIG THANK YOU for clearing the confusion. Happy New year 2019 to you ! :)

                  – Prashant Mishra
                  Jan 1 at 7:04

















                Thanks... Worked for while loop.Can you also tell me why this code is not working with For loop.. def askplayerchoice(): playerchoice = '' for playerchoice not in ('X' , 'O'): playerchoice = input('Enter X or O: ') if playerchoice == 'X': return ['X' , 'O'] else: return ['O', 'X'] askplayerchoice()

                – Prashant Mishra
                Jan 1 at 6:57







                Thanks... Worked for while loop.Can you also tell me why this code is not working with For loop.. def askplayerchoice(): playerchoice = '' for playerchoice not in ('X' , 'O'): playerchoice = input('Enter X or O: ') if playerchoice == 'X': return ['X' , 'O'] else: return ['O', 'X'] askplayerchoice()

                – Prashant Mishra
                Jan 1 at 6:57






                1




                1





                @PrashantMishra, for does not work like while. for x in (..,..) will take values from (.., ..) one item at a time in each iteration. Try printing: for x in (1,2): print(x). What you did for .. not in (.., ..) is syntactically wrong.

                – Austin
                Jan 1 at 7:01





                @PrashantMishra, for does not work like while. for x in (..,..) will take values from (.., ..) one item at a time in each iteration. Try printing: for x in (1,2): print(x). What you did for .. not in (.., ..) is syntactically wrong.

                – Austin
                Jan 1 at 7:01













                yes, you are right.. I got it now !! BIG THANK YOU for clearing the confusion. Happy New year 2019 to you ! :)

                – Prashant Mishra
                Jan 1 at 7:04





                yes, you are right.. I got it now !! BIG THANK YOU for clearing the confusion. Happy New year 2019 to you ! :)

                – Prashant Mishra
                Jan 1 at 7:04













                2














                You can add a try catch block and throw an exception when the entered string does not match your desired value. I have updated your code for the same. Below is the snippet :



                def askplayerchoice():
                playerchoice = ''
                while playerchoice.lower() not in ('X' , 'O'):
                try:
                playerchoice = str(input('Enter X or O: '))
                if playerchoice.lower() not in ['x','o']:
                raise ValueError('A very specific bad thing happened.')
                if playerchoice.lower() == 'x':
                return ['X' , 'O']
                else:
                return ['O', 'X']
                except ValueError:
                playerchoice = ''


                askplayerchoice()





                share|improve this answer




























                  2














                  You can add a try catch block and throw an exception when the entered string does not match your desired value. I have updated your code for the same. Below is the snippet :



                  def askplayerchoice():
                  playerchoice = ''
                  while playerchoice.lower() not in ('X' , 'O'):
                  try:
                  playerchoice = str(input('Enter X or O: '))
                  if playerchoice.lower() not in ['x','o']:
                  raise ValueError('A very specific bad thing happened.')
                  if playerchoice.lower() == 'x':
                  return ['X' , 'O']
                  else:
                  return ['O', 'X']
                  except ValueError:
                  playerchoice = ''


                  askplayerchoice()





                  share|improve this answer


























                    2












                    2








                    2







                    You can add a try catch block and throw an exception when the entered string does not match your desired value. I have updated your code for the same. Below is the snippet :



                    def askplayerchoice():
                    playerchoice = ''
                    while playerchoice.lower() not in ('X' , 'O'):
                    try:
                    playerchoice = str(input('Enter X or O: '))
                    if playerchoice.lower() not in ['x','o']:
                    raise ValueError('A very specific bad thing happened.')
                    if playerchoice.lower() == 'x':
                    return ['X' , 'O']
                    else:
                    return ['O', 'X']
                    except ValueError:
                    playerchoice = ''


                    askplayerchoice()





                    share|improve this answer













                    You can add a try catch block and throw an exception when the entered string does not match your desired value. I have updated your code for the same. Below is the snippet :



                    def askplayerchoice():
                    playerchoice = ''
                    while playerchoice.lower() not in ('X' , 'O'):
                    try:
                    playerchoice = str(input('Enter X or O: '))
                    if playerchoice.lower() not in ['x','o']:
                    raise ValueError('A very specific bad thing happened.')
                    if playerchoice.lower() == 'x':
                    return ['X' , 'O']
                    else:
                    return ['O', 'X']
                    except ValueError:
                    playerchoice = ''


                    askplayerchoice()






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 1 at 7:09









                    Chintan BhattChintan Bhatt

                    212




                    212























                        0














                        Your function is returning a value within the while loop, regardless of what the user input is, and that's causing the loop to end. You need to change your else condition to else if:



                        if playerchoice == 'X':
                        return ['X' , 'O']
                        elif playerchoice == 'O':
                        return ['O', 'X']





                        share|improve this answer
























                        • Thanks.. What is wrong in this condition: for playerchoice not in ('X' , 'O'): playerchoice = input('Enter X or O: ')

                          – Prashant Mishra
                          Jan 1 at 7:02
















                        0














                        Your function is returning a value within the while loop, regardless of what the user input is, and that's causing the loop to end. You need to change your else condition to else if:



                        if playerchoice == 'X':
                        return ['X' , 'O']
                        elif playerchoice == 'O':
                        return ['O', 'X']





                        share|improve this answer
























                        • Thanks.. What is wrong in this condition: for playerchoice not in ('X' , 'O'): playerchoice = input('Enter X or O: ')

                          – Prashant Mishra
                          Jan 1 at 7:02














                        0












                        0








                        0







                        Your function is returning a value within the while loop, regardless of what the user input is, and that's causing the loop to end. You need to change your else condition to else if:



                        if playerchoice == 'X':
                        return ['X' , 'O']
                        elif playerchoice == 'O':
                        return ['O', 'X']





                        share|improve this answer













                        Your function is returning a value within the while loop, regardless of what the user input is, and that's causing the loop to end. You need to change your else condition to else if:



                        if playerchoice == 'X':
                        return ['X' , 'O']
                        elif playerchoice == 'O':
                        return ['O', 'X']






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jan 1 at 5:52









                        kavehkaveh

                        7331222




                        7331222













                        • Thanks.. What is wrong in this condition: for playerchoice not in ('X' , 'O'): playerchoice = input('Enter X or O: ')

                          – Prashant Mishra
                          Jan 1 at 7:02



















                        • Thanks.. What is wrong in this condition: for playerchoice not in ('X' , 'O'): playerchoice = input('Enter X or O: ')

                          – Prashant Mishra
                          Jan 1 at 7:02

















                        Thanks.. What is wrong in this condition: for playerchoice not in ('X' , 'O'): playerchoice = input('Enter X or O: ')

                        – Prashant Mishra
                        Jan 1 at 7:02





                        Thanks.. What is wrong in this condition: for playerchoice not in ('X' , 'O'): playerchoice = input('Enter X or O: ')

                        – Prashant Mishra
                        Jan 1 at 7:02











                        0














                        First you were initializing playerchoice = '' but inside the loop you were only checking for playerchoice == 'X'. But you didn't check for playerchoice == 'O'. therefore it went to the else and got out of the loop.



                        This should do the work:



                        def askplayerchoice():
                        playerchoice = input('Enter X or O: ')
                        while playerchoice not in('X', 'O'):
                        playerchoice = input('Enter X or O: ')
                        if playerchoice == 'X':
                        return ['X', 'O']
                        elif playerchoice == 'O':
                        return ['O', 'X']
                        askplayerchoice()





                        share|improve this answer






























                          0














                          First you were initializing playerchoice = '' but inside the loop you were only checking for playerchoice == 'X'. But you didn't check for playerchoice == 'O'. therefore it went to the else and got out of the loop.



                          This should do the work:



                          def askplayerchoice():
                          playerchoice = input('Enter X or O: ')
                          while playerchoice not in('X', 'O'):
                          playerchoice = input('Enter X or O: ')
                          if playerchoice == 'X':
                          return ['X', 'O']
                          elif playerchoice == 'O':
                          return ['O', 'X']
                          askplayerchoice()





                          share|improve this answer




























                            0












                            0








                            0







                            First you were initializing playerchoice = '' but inside the loop you were only checking for playerchoice == 'X'. But you didn't check for playerchoice == 'O'. therefore it went to the else and got out of the loop.



                            This should do the work:



                            def askplayerchoice():
                            playerchoice = input('Enter X or O: ')
                            while playerchoice not in('X', 'O'):
                            playerchoice = input('Enter X or O: ')
                            if playerchoice == 'X':
                            return ['X', 'O']
                            elif playerchoice == 'O':
                            return ['O', 'X']
                            askplayerchoice()





                            share|improve this answer















                            First you were initializing playerchoice = '' but inside the loop you were only checking for playerchoice == 'X'. But you didn't check for playerchoice == 'O'. therefore it went to the else and got out of the loop.



                            This should do the work:



                            def askplayerchoice():
                            playerchoice = input('Enter X or O: ')
                            while playerchoice not in('X', 'O'):
                            playerchoice = input('Enter X or O: ')
                            if playerchoice == 'X':
                            return ['X', 'O']
                            elif playerchoice == 'O':
                            return ['O', 'X']
                            askplayerchoice()






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Jan 1 at 6:01

























                            answered Jan 1 at 5:54









                            Partho63Partho63

                            1,8391823




                            1,8391823























                                0














                                When you use return, the while loop will be stopped.
                                Try this code, it will keep asking.



                                def askplayerchoice():
                                playerchoice = ''
                                while playerchoice not in ('X' , 'O'):
                                playerchoice = input('Enter X or O: ')
                                if playerchoice == 'X':
                                print('X' , 'O')
                                else:
                                print('O', 'X')
                                return askplayerchoice()
                                askplayerchoice()





                                share|improve this answer




























                                  0














                                  When you use return, the while loop will be stopped.
                                  Try this code, it will keep asking.



                                  def askplayerchoice():
                                  playerchoice = ''
                                  while playerchoice not in ('X' , 'O'):
                                  playerchoice = input('Enter X or O: ')
                                  if playerchoice == 'X':
                                  print('X' , 'O')
                                  else:
                                  print('O', 'X')
                                  return askplayerchoice()
                                  askplayerchoice()





                                  share|improve this answer


























                                    0












                                    0








                                    0







                                    When you use return, the while loop will be stopped.
                                    Try this code, it will keep asking.



                                    def askplayerchoice():
                                    playerchoice = ''
                                    while playerchoice not in ('X' , 'O'):
                                    playerchoice = input('Enter X or O: ')
                                    if playerchoice == 'X':
                                    print('X' , 'O')
                                    else:
                                    print('O', 'X')
                                    return askplayerchoice()
                                    askplayerchoice()





                                    share|improve this answer













                                    When you use return, the while loop will be stopped.
                                    Try this code, it will keep asking.



                                    def askplayerchoice():
                                    playerchoice = ''
                                    while playerchoice not in ('X' , 'O'):
                                    playerchoice = input('Enter X or O: ')
                                    if playerchoice == 'X':
                                    print('X' , 'O')
                                    else:
                                    print('O', 'X')
                                    return askplayerchoice()
                                    askplayerchoice()






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Jan 1 at 6:03









                                    WEN WENWEN WEN

                                    9828




                                    9828






























                                        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%2f53993274%2fthe-while-loop-is-not-repeating-itself-upon-throwing-garbage-values%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

                                        MongoDB - Not Authorized To Execute Command

                                        How to fix TextFormField cause rebuild widget in Flutter

                                        in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith