Home > Blockchain >  How to confirm or validate the inputted word from the list on Python?
How to confirm or validate the inputted word from the list on Python?

Time:10-26

I had an issue validating the inputted word from the list before proceeding to the next function for the text to be created.

while True:
    try:
        services = ['Conference','Dinner','Lodging','Membership Renewal']
        for i in range(0,4):
            print(f"{services[i] : <14}")
        hotel_services = str(input("Enter the hotel services: "))
        if hotel_services == services:
            print("Valid")
    except ValueError:
        print("Invalid")
    else:
        break
    print("Try Again")

I would like to have it said "Invalid" when the user types a wrong services. Thank you!

CodePudding user response:

You can check if a string exists in a list using the in keyword as such:

if hotel_services in services:
    print('Valid!')
else:
    print('Invalid!')

CodePudding user response:

Your code can be rewritten as

while True:
    try:
        services = ['Conference','Dinner','Lodging','Membership Renewal']
        for service in services:
            print(f"{service : <14}")
        hotel_services = str(input("Enter the hotel services: "))
        if hotel_services in services:
            print("Valid")
        else:
            print("Invalid")
    except ValueError:
        print("Invalid")
    else:
        break
    print("Try Again")

I am not sure about the exception. It may never show up

  • Related