5
\$\begingroup\$

I have a list

list = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

If I give an input of Saturday, then it should return the next day (Sunday) and the previous day (Friday). My program works, but I am looking for a simple function to print the next value in the list for a given item.

My code below :

list = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
give_day = input('Enter the day : ')
index_give_day = list.index(give_day)
len_list = len(list)-1 
next_day = list[0 if index_give_day == len_list else index_give_day +1]
prev_day = list[index_give_day -1]
print(next_day)
print(prev_day)
\$\endgroup\$

2 Answers 2

7
\$\begingroup\$

Don't make the list yourself; use calendar.day_name. Among other reasons, this will support localisation, where your current code does not.

You don't need conditionals, and you don't even need to modulate your index. Since the array is so small, the simplest indexing solution is probably just to duplicate it and index directly.

Consider applying .title() for a more forgiving name lookup.

Suggested

from calendar import day_name

weekdays = tuple(day_name)*2

name = input('Enter the weekday name: ').title()
day = weekdays.index(name)
prev_day, next_day = weekdays[day-1], weekdays[day+1]
print(next_day)
print(prev_day)

Output

Enter the weekday name: saturday
Sunday
Friday
\$\endgroup\$
6
\$\begingroup\$

PEP 8 and naming

You named your variables according to PEP 8 and also gave them reasonable names, with some exceptions:

  1. list. It overrides a built-in type and does not convey what it contains. Consider renaming it WEEKDAYS as it represents a global constant.
  2. give_day actually reads the current day from the user, so current_day would be more appropriate
  3. ... and so would be current_day_index instead of index_give_day.

Also note that PEP 8 wants you to put a space after a comma in e.g. list definitions.

Input validation

You never validate the input of the user. If they enter an invalid day, the program will terminate with a ValueError.

Know your requirements

Your title only mentions returning the next day, but the program also calculates the previous day. Is this necessary?

Use functions

Currently your code only works as an isolated script. There is no reusability. Consider putting the code that returns the next item of an arbitrary list into a function

Putting it together

#! /usr/bin/env python3

from os import linesep
from typing import Any


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


def neighbors(item: Any, items: list[Any]) -> tuple[Any, Any]:
    """Return the predecessor and successor entry
    for the item of the given list.
    """
    
    return (
        items[(index := items.index(item)) - 1],
        items[(index + 1) % len(items)]
    )


def main() -> None:
    """Run main program."""

    current_day = input('Enter the day : ')
    
    try:
        previous_day, next_day = neighbors(current_day, WEEKDAYS)
    except ValueError:
        print('Invalid weekday:', current_day)
    else:
        print(previous_day, next_day, sep=linesep)


if __name__ == '__main__':
    main()
\$\endgroup\$
2
  • 1
    \$\begingroup\$ I would have structured it like day_before and day_after but I guess that's a pretty arbitrary choice. Looks nice! \$\endgroup\$
    – JollyJoker
    Commented Aug 22, 2022 at 15:50
  • 1
    \$\begingroup\$ I would've moved the walrus assignment out of the return statement, as the current implementation may be confusing to a reader. \$\endgroup\$ Commented Aug 22, 2022 at 22:51

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.