Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading