Search code examples
pythonfor-loopbreak

for loop break statment


city_flight = input("London, Edinburgh, Liverpool, Manchester"'\t').lower()    
for city in city_flight:
        if city != "London" and city != "Edinburgh" and city != "Liverpool" and city != "Manchester":
            print("Enter the city properly")
        break
        num_nights = int(input("How many nights prefer to stay?" '\t'))
        rental_days = int(input("How many days rent a car?" '\t'))

I have tried so many times and stuck break statement not working, I want if the condition is not met go back to the first line of code. so any help would be greatly appreciated.


Solution

  • Doing a for loop over city_flight is just iterating over the individual characters in the string -- instead, use a while True loop that includes the thing that you want to repeat (the input() call), and break it when the input is correct:

    while True:
        city = input("London, Edinburgh, Liverpool, Manchester\t").lower()    
        if city in {"london", "edinburgh", "liverpool", "manchester"}:
            break  # end loop and continue to num_nights etc
        print("Enter the city properly")  # repeat the loop
    
    num_nights = int(input("How many nights prefer to stay?\t"))
    rental_days = int(input("How many days rent a car?\t"))
    

    You can also eliminate some duplication by putting the cities in a list and using that for both your input text and the validation, e.g.:

    cities = ["London", "Edinburgh", "Liverpool", "Manchester"]
    while True:
        city = input(", ".join(cities) + "\t").title()
        if city in cities:
            break
        # etc