gpt4 book ai didi

python - 如果一部分失败,请重新启动异常处理

转载 作者:行者123 更新时间:2023-12-03 08:04:42 24 4
gpt4 key购买 nike

我有以下片段:

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

我该如何重写它,以使如果任何检查功能失败,它将再次从 b = raw_input行开始并重新测试所有检查。

更新
在听取了keithjgrant和m1k3y02的建议后,我对代码进行了改进,但是它无法正常工作。如果我连续输入“1”,它将在不同的异常之间反弹,而不是停留在第一张支票上。
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

最佳答案

从目前的 Angular 来看,您的问题与异常(exception)无关。请尝试以下操作:

checks = [
lambda n: (len(n)==4, "Enter 4 digits only."),
lambda n: (n.isdigit(), "Enter digits only."),
lambda n: (len(set(str(n)))==4, "Enter non duplicate numbers only.")
]

a = raw_input("Enter the 4 numbers you want to play with: ")

sturn = 1
lturn = 8
for turn in range(sturn, lturn):
b = raw_input("Enter your guess: ")
all_good = True

for check in checks:
good,msg = check(b)
if not good:
print msg
all_good = False
break

if all_good:
print "{0} is correct!".format(b)
break

您可以重写它以使用异常,如下所示:
class CheckError(Exception): pass

class WrongLengthError(CheckError): pass
def check1(n):
if len(n) != 4:
raise WrongLengthError("Enter 4 digits only.")

class NonDigitCharError(CheckError): pass
def check2(n):
if not n.isdigit():
raise NonDigitCharError("Enter digits only.")

class HasDuplicatesError(CheckError): pass
def check3(n):
if len(set(str(n))) != 4:
raise HasDuplicatesError("Enter non duplicate numbers only.")


a = raw_input("Enter the 4 numbers you want to play with: ")

sturn = 1
lturn = 8
for turn in range(sturn, lturn):
b = raw_input("Enter your guess: ")

try:
for check in (check1, check2, check3):
check(b)

print "{0} is correct!".format(b)
break
except CheckError, c:
print c

关于python - 如果一部分失败,请重新启动异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4765320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com