基本上,我正在建立一个汽车销售计划,其中汽车及其细节被添加到一个类(然后是文本文件,但该部分与我需要的帮助无关)。我正在使用for循环'for x in range(nocars)'来做到这一点。我的输入都在没有验证的情况下工作但现在我需要进行验证,这是我用'carYear'变量完成的,你可以看到while循环。基本上如果年份低于1900,它将继续提示用户重新输入正确的值(每次输入不正确)。到目前为止,这在程序中有效。一旦输入正确的数字,程序应该转到下一个输入下一个变量。然而,它只是再次启动范围过程。我知道这是由'break'引起的,但是我还不知道还有什么方法可以在恢复输入过程时退出while循环。救命?虽然循环被双星号包围,所以你可以找到它。感谢。
for x in range(nocars):
print("Car No.", x+1)
carMake = input("Please enter make: ")
carModel = input("Please enter model: ")
carYear = input("Please enter year of manufacture: ")
**while int(carYear) < 1900 :
carYear = input("Please enter a valid value: ")
else:
break**
carLitre = input("Please enter the cylinder capacity of the car in litres : ")
carVal = input("Please enter value in GBP: ")
carReg = input("Please enter registration number (excluding spaces): ")
carOwn = input("Please enter the previous ownership (new, second-hand, third-hand, more than three previous owners): ")
carMile = input("Please enter the mileage: ")
carMod = input("Please enter any modiciations existing on the car. If there are no modifications, enter 'None': ")
carCond = input("Please enter the condition of the car (VP = Very Poor, P = Poor, A = Average, G = Good, VG = Very Good, P = Pristine: ")
print("-Customer Details-")
cusName1 = input("Please enter your forename: ")
cusName2 = input("Please enter your surname: ")
cusGen = input("Please enter your gender (Male, Female, Other): ")
cusAge = input("Please enter your age: ")
print ("----------")
print("You have added car(s) to temporary memory. To save this to a text file, select '3' from the following menu and follow the steps...")
carList.append(CarEntry(carMake, carModel, carYear, carLitre, carVal, carReg, carOwn, carMile, carMod, carCond, cusName1, cusName2, cusGen, cusAge))
答案 0 :(得分:0)
你应该在不同的功能中进行验证,如下所示:
carYear = validNumberInput('Please enter the year of manufacture: ', 1900)
将功能分开如下:
def validNumberInput(prompt, minimum):
while True:
try:
value = int(input(prompt))
except ValueError:
continue
if value >= minimum:
return value
然后根据需要使用不同的提示调用该函数。
您需要为不同类型的验证编写不同的函数,例如空字符串,无效数字,数字范围等。
答案 1 :(得分:0)
while-else构造可能没有做你想要的。在else之后的break实际上导致外部for循环中断。尝试摆脱其他部分,看起来像:
while int(carYear) < 1900 :
carYear = input("Please enter a valid value: ")
carLitre = input("Please enter the cylinder capacity of the car in litres : ")
carVal = input("Please enter value in GBP: ")
...