Search code examples
pythonloopsinputwhile-loopback

Is there a way to loop back to the beginning of a certain part of the code in python


I was writting a script to check if the lenght of an input word is equal to a certain number, and if not loop back again to the the input question.

I used the following code,

x=input("input a word")

y=len(x)

while y<8 or 8<y:

  print("word must have 8 
         characters")

    continue

  print("word accepted")

    break

But the problem is when looping back using "continue" it won't loop back to the input question. Also input question can't be written inside the while loop because it gives out an error "x is not defined".

So how can I loop back to the input question in here.Is there anyway to do that.


Solution

  • Two ways of doing it, using a while True:

    while True:
        x=input("input a word: ")
        if len(x) == 8:
            break
        print("word must have 8 characters")
    

    Using recursion:

    def get_input():
        x=input("input a word: ")
        if len(x) == 8:
            return x
        print("word must have 8 characters")
        return get_input()