0

I am doing some practice on graph data structures using a small railway network. In the beginning, I ask for a starting destination and an end destination from the user. The user inputs must be a value from a list of destinations. What I've written so far:

        a = 0
        b = 0

        while a == 0:
            start_point = input("\nWhat is your starting location?\n").title()
            if start_point in valid_destinations:
                print("That is a valid starting location.")
                a = 1
            else:
                print("Please choose one of the cities in our network.")
                continue

        while b == 0:
            end_point = input("\nWhat is your destination\n").title()
            if end_point in valid_destinations:
                print("That is a valid destination.")
                b = 1
            else:
                print("Please choose one of the cities in our network.")
                continue

Because they are separate questions, does that mean there must be separate while loops? I tried doing them both within one but I couldn't get the validation function to work properly. It functions as written above but I feel it could be more efficient with less repetition.

MarquisMark
  • 37
  • 1
  • 7
  • you don't need `continue`, loops continue automatically unless you tell them to stop. – Barmar May 16 '20 at 07:06
  • Use `break` to break out of a loop rather than setting a variable. – Barmar May 16 '20 at 07:06
  • 2
    Yes, a separate loop is needed for each. If you have to do this repeatedly, put it into a function so you don't have to repeat the same code over and over. – Barmar May 16 '20 at 07:07
  • see also : https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response?rq=1 – Joran Beasley May 16 '20 at 07:11

1 Answers1

0

You can write both questions inside one while loop, you just have to change a little how you check the values: It could be something like the code below, where you first check if the variables have the default value (in which case the user should write their input), and then check if the input is valid.

a, b = None, None # You could also use 0

while a is None or b is None:
    if a is None: # a == 0
        a = input('write start location: ').title()
    if a not in valid_destinations:
        a = None
        print('Choose a valid start location.')
        continue

    if b is None: # b == 0
        b = input('write destination: ').title()
    if b not in valid_destinations:
        b = None
        print('Choose a valid destination.')

The condition in the while loop makes that there are no unnecessary repetitions and that it stops when both inputs are valid.

scf.12
  • 58
  • 1
  • 6