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.
CodePudding user response:
The length is already assigned before while
loop, so you will never get a new input. You have to get an input inside while
loop, so that you can get a new input again and again.
This works as you want:
while True:
x = input("input a word: ")
if len(x) != 8:
print("word must have 8 characters")
continue
else:
print("word accepted")
break
CodePudding user response:
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()
CodePudding user response:
while True==True:
x=input("input a word")
y=len(x)
if y==8:
print("word accepted")
break
else:
print("word must have 8 characters")
# continue