I have the following snippet:
def check1(n):
if len(n) != 4:
return raw_input("Enter 4 digits only")
else:
return True
def check2(n):
if n.isdigit() != True:
return raw_input("Enter digits only")
else:
return True
def check3(n):
if len(set(str(n))) != 4:
return raw_input("Enter non duplicate numbers only")
else:
return True
sturn = 1
lturn = 8
a = raw_input("Enter the 4 numbers you want to play with: ")
for turn in range(sturn, lturn):
b = raw_input("Enter your guess: ")
if (check1(b) != True or check2(b) != True or check3(b) != True):
if check1(b) != True:
print check1(b)
elif check2(b) != True:
print check2(b)
elif check3(b) != True:
print check3(b)
else:
print b
How can I rewrite this such that if any of the check functions fail, it starts from the b = raw_input line again and retests all the checks.
UPDATE
I’ve improved the code after heeding the advice from keithjgrant and m1k3y02 but it doesn’t work properly. If I enter ‘1’ consecutively, it bounces between different exceptions instead of staying on the first check.
def checks(n):
if len(n) != 4 or n.isdigit() != True or len(set(str(n))) != 4:
return False
else:
return True
sturn = 1
lturn = 8
a = raw_input("Enter the 4 numbers you want to play with: ")
for turn in range(sturn, lturn):
b = raw_input("Enter your guess: ")
while checks(b) != True:
if len(b) != 4:
b = raw_input("Enter 4 digits only")
if b.isdigit() != True:
b = raw_input("Enter digits only")
if len(set(str(b))) != 4:
b = raw_input("Enter non duplicate numbers only")
print b
Your question, as it stands, has nothing to do with exceptions. Try the following:
You could rewrite it to use exceptions as follows: