pythondata-structurescontrol-structure

Check for correct user input without exiting loop


I'm trying to write a travel itinerary program using base Python functionality. In step 1, the program should ask for primary customer (making the booking) details viz name and phone number. I've written code to also handle errors like non-alphabet name entry, errors in phone number input (ie phone number not numeric, not 10 digits etc) to keep asking for valid user input, as below, which seems to work fine:

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


For the next step, the program should ask for details of all passenger ie name, age and phone numbers and store them. I want to implement similar checks as above but my code below simply exits the loop once the number of travellers (num_travellers, 2 in this case) condition is met, even if there are errors in input:

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

I've tried using a while loop like mentioned in this thread but doesn't seem to work. Where am I going wrong? Thanks


Solution

  • You have missed while True: loop when asking for passenger data. Try something like below:

    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
    

    BTW I moved travellers variable out of the loop, otherwise it is going to be cleared on every iteration.