Home>
import datetime
d= datetime.datetime.now ()
if d.isoweekday ()== 1:
    d_2= '*** [' + d.strftime ("% d.% m") + ']' + mon_1 + '\ n'
elif d.isoweekday ()== 2:
    d_2= '*** [' + d.strftime ("% d.% m") + ']' + tue_1 + '\ n'
elif d.isoweekday ()== 3:
    d_2= '*** [' + d.strftime ("% d.% m") + ']' + wed_1 + '\ n'
elif d.isoweekday ()== 4:
    d_2= '*** [' + d.strftime ("% d.% m") + ']' + thu_1 + '\ n'
elif d.isoweekday ()== 5:
    d_2= '*** [' + d.strftime ("% d.% m") + ']' + fri_1 + '\ n'
elif d.isoweekday ()== 6:
    d_2= '*** [' + d.strftime ("% d.% m") + ']' + sat_1 + '\ n'
elif d.isoweekday ()== 7:
    d_2= '*** [' + tomorrow.strftime ("% d.% m") + ']' + mon_2

Here, in fact, is the assignment of a variable to a certain value depending on the current date (Monday -mon, etc.). Is it possible to somehow loop this piece of code?

Tip: use string formatting and avoid repeating code

gil9red2021-11-25 03:30:49

What's stored in the variables mon_1, tue_1, etc.? You may have invented an existing bicycle.

Эникейщик2021-11-25 03:30:49
  • Answer # 1

    An example of code looping (+ a little refactoring):

    import datetime as DT
    import time
    PATTERN_STR= '*** [{:% d.% M}] {} \ n'
    while True:
        d= DT.datetime.now ()
        weekday= d.isoweekday ()
        if weekday== 1:
            d_2= PATTERN_STR.format (d, mon_1)
        elif weekday== 2:
            d_2= PATTERN_STR.format (d, tue_1)
        elif weekday== 3:
            d_2= PATTERN_STR.format (d, wed_1)
        elif weekday== 4:
            d_2= PATTERN_STR.format (d, thu_1)
        elif weekday== 5:
            d_2= PATTERN_STR.format (d, fri_1)
        elif weekday== 6:
            d_2= PATTERN_STR.format (d, sat_1)
        else:
            d_2= PATTERN_STR.format (tomorrow, mon_2)
        print (d_2)
        # Delay for 5 minutes
        time.sleep (5 * 60)
    

    With a lot of refactoring:

    • Using a dictionary to get rid of the heapif/else

    Example:

    ...
    WEEKDAY_BY_STR= {
        1: mon_1,
        2: tue_1,
        3: wed_1,
        4: thu_1,
        5: fri_1,
        6: sat_1,
        7: mon_2,
    }
    while True:
        d= DT.datetime.now ()
        weekday= d.isoweekday ()
        # For weekday== 7, another date is needed -tomorrow
        if weekday== 7:
            d= tomorrow
        d_2= PATTERN_STR.format (d, WEEKDAY_BY_STR [weekday])
        print (d_2)
        # Delay for 5 minutes
        time.sleep (5 * 60)