0

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!!!

2
  • 1
    What have you tried? This is not a code-writing service for homework. Commented Nov 16, 2022 at 6:51
  • Yeah, I see how it looks like a kid’s homework assignment. I’m a 69-year-old retired academic trying to learn Python. I’ve tried several approaches including while loop, try-else, if any(), and if-else. Commented Nov 16, 2022 at 7:22

2 Answers 2

0

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
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the coding example!
I'm relatively new to Python and I was able to get this code to work on my RPi running Thonny. When I copied the code to an online Python code tester (programiz.com/python-programming/online-compiler) I received errors for both function definitions. I naively shortened both definitions to the basic syntax and the code still worked locally and it worked on the online Python compiler. The shortened function definitions are: def validate_days(days): and def askfordays(): Maybe 0x0fba can comment???
The "enriched" syntax is is known as type hinting and "does not interfere with the way your program would otherwise run". Type hints are just here to indicate the type of the arguments expected and also the return type. Optionally mypy - a static type checker - can be used to "enforce" that types are respected. The syntax I used works only for Python 3.10+. If your Rpi accepts that syntax it means that it is a version >= 3.10. I had a look at the Python interpreter provided by programmiz but haven't found the Python version. Doesn't accept import sys print(sys.version).
Anyway it's a version < 3.10. It works with just minor changes. Add this import at the beginning : from typing import List Update the functions signatures : def validate(days: List[str]) -> None: def askfordays(ntimes: int = 3) -> List[List[str]]: That's all to make it work.
Thanks for the thorough explanation and additional insight!
0

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\n")
    user_entry = input("Please enter the day(s) of the week: ").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()
list2 = validate_entry()
list3 = validate_entry()

print(f"{list1} \n{list2} \n{list3}")

Output:

['Monday','Wednesday','Friday']
['Tuesday','Friday']
['Wednesday']

1 Comment

Thanks for the coding example!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.