Home > Mobile >  Python validate user input of multiple strings
Python validate user input of multiple strings

Time:11-16

I've been working on this all day and can't get it done. Any help will be much appreciated! In Python, I want to loop through 3 times asking the user to enter 1 or more days of the week (e.g., Please enter the day(s) of the week:) with the input ending up in a list. The resulting data could look like this:

List1 = ['Monday','Wednesday','Friday']
List2 = ['Tuesday','Friday']
List3 = ['Wednesday']

In addition, I want to validate the input so that I know that each entered day is spelled correctly with appropriate capitalization. The only valid entries are Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday.

Suggestions??? Thanks!!!

CodePudding user response:

Use askfordays() to ask the user for days (3 times is the default). It returns a list of lists.

According to your example, you can use it like this : list1, list2, list3 = askfordays()

The validate() function doesn't return anything. Its only purpose is to raise a ValueError Exception if input is not correct.

The validate() function is called inside a "user input" loop, that loops until input is correct.

WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

def validate(days: list[str]) -> None:
    for day in days:
        if day not in WEEKDAYS:
            raise ValueError(f"Unknown day : {day}")

def askfordays(ntimes: int = 3) -> list[list[str]]:
    res = []
    for _ in range(ntimes):
        while True:  # loop until user input is correct
            days = input("Please enter the day(s) of the week (comma-separated) :\n")
            days = [d.strip() for d in days.split(",")]
            try:
                validate(days)
            except ValueError as e:
                print(e)
            else:
                res.append(days)
                break
    return res

CodePudding user response:

Just create a function and call it as many times as you want.

valid_days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

def validate_entry():
    new_list = []
    print("NOTE: Seperate days with comma(,) E,g: Sunday, Monday")
    user_entry = input("Enter days(s): ").title()
    if ", " or "," in user_entry:
        for day in user_entry.split(","):
            day = day.strip()
            if day in valid_days:
                new_list.append(day)
            else:
                print(f"{day} is not a correct spelling.")
    return new_list
    
    
list1 = validate_entry()
print(list1)

list2 = validate_entry()
print(list2)

list3 = validate_entry()
print(list3)
  • Related