0

I want the code to repeat itself if the user has given invalid input. Another way to ask would be :

ans2 = input ('Do you want to continue (y/n)')
if ans2 == 'y':
#repeat the code and I don't know how to do that
if ans2 == 'n':
print ('Ok Goodbye')
exit
  • We would need more details including the actual code and what the "invalid input" could be. Right now, you don't mention the "first way", only "another way" where you're asking for y or n, which will both be valid, not invalid. So it's unclear what you actually mean. – Jesper Oct 10 '20 at 15:13
  • The questioner wants the answer for the another way only – Yeshwin Verma Oct 10 '20 at 15:15
  • More details needed, but probably: https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response – Wups Oct 10 '20 at 15:19
  • Also, you won't need `exit` at the end of the code because python quits automatically once the script has finished executing. – BBloggsbott Oct 10 '20 at 15:28
  • Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – BBloggsbott Oct 10 '20 at 15:29

3 Answers3

1

you can put it into loop

while True:
    data = input("Enter data: ")

    if <valid_condition>:
        # do something
        ans2 = input('Do you want to continue (y/n)')
        if ans2 == "y":
            continue
        else:
            break
    else:
        print("Invalid data")
        ans2 = input('Do you want to continue (y/n)')
        if ans2 == "y":
            continue
        else:
            break
        
Carlos
  • 452
  • 2
  • 18
0

It's a fairly common structure.

def yourcode():
   pass  # your code here

ans2 = ''
while not ans2 in ['y','n']:
   ans2 = input ('Do you want to continue (y/n)')
   if ans2 == 'y':
      yourcode()
      ans2 = ''
   elif ans2 == 'n':
      print ('Ok Goodbye')
      exit
   else:
      print('Invalid response')
Mike67
  • 11,175
  • 2
  • 7
  • 15
-1

You could define the code in function like below and you can call the function at the end and to repeated it again call it

def function():
    ans2 = input ('Do you want to continue (y/n)')
    if ans2 == 'y':
        function()
    if ans2 == 'n':
        print ('Ok Goodbye')
        sys.exit()
function()
Yeshwin Verma
  • 282
  • 3
  • 16