在不退出循环的情况下检查用户输入是否正确

Check for correct user input without exiting loop

我正在尝试使用基本 Python 功能编写旅行行程计划。在第 1 步中,程序应询问主要客户(进行预订)的详细信息,即姓名和 phone 号码。我编写了代码来处理非字母名称输入、phone 数字输入错误(即 phone 数字不是数字、不是 10 位数字等)以继续询问有效的用户输入,因为下面,这似乎工作正常:

while True:
    cust_name = input("Please enter primary customer name: ")
    if cust_name.isalpha():
        break
    else:
        print("Please enter valid name")
        continue
    
while True:
    cust_phone = input("Please enter phone number: ")
    if cust_phone.isnumeric() and len(cust_phone) == 10:
        break
    else:
        print("Error! Please enter correct phone number")
        continue

while True:
    num_travellers = input("How many people are travelling? ")
    if int(num_travellers) >= 2:
        break
    else:
        print("Please enter at least two passengers")
        continue
Output:

Please enter primary customer name: sm
Please enter phone number: 1010101010
How many people are travelling? 2


对于下一步,程序应该询问所有乘客的详细信息,即姓名、年龄和 phone 号码并存储它们。我想实现与上面类似的检查,但我下面的代码只是在满足旅客数量(num_travellers,在本例中为 2)条件后退出循环,即使输入有错误:

for i in range(int(num_travellers)):
    travellers = []
    travel_name = input("Please enter passenger name: ")
    if travel_name.isalpha():
        travellers.append(travel_name)
    else:
        print("Please enter valid name")
        continue
for j in range(int(num_travellers)):
    travel_age = []
    age = input("Please enter passenger age: ")
    if age.isnumeric():
        travel_age.append(age)
    else:
        print("Please enter valid age")
        continue

Output:
 
Please enter passenger name: 23
Please enter valid name
Please enter passenger name: 34
Please enter valid name
Please enter passenger age: sm
Please enter valid age
Please enter passenger age: sk
Please enter valid age
Please enter passenger age: sk

我试过使用 this 线程中提到的 while 循环,但似乎不起作用。我哪里错了?谢谢

您在询问乘客数据时错过了 while True: 循环。试试下面的方法:

travellers = []
for i in range(int(num_travellers)):
    while True:
        travel_name = input("Please enter passenger name: ")
        if travel_name.isalpha():
            travellers.append(travel_name)
            break
        else:
            print("Please enter valid name")
            continue

顺便说一句,我将 travelers 变量移出了循环,否则它会在每次迭代时被清除。