-1

I've been trying to fix this code for an hour and I don't quite understand how it's accessing one of the other lists when it's not meant to. For example when I pick a day then I ask for it to be a character (char) then it just outputs the full day...same thing happens with a short day.

class dateformat:
    def __init__(self):
        self.dyfull = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
                       "Sunday"]
        self.shortdy = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
        self.chardy = ["M", "T", "W", "T", "F", "S", "S"]
        self.dy = 0
        self.formt = ""
        pass

    def getday(self):
        self.day = int(input("What day is it? (Number): ")) - 1

    def getformat(self):
        self.formt = str(input("What format would you like? "
                               "[Day, Shortday, Char]: "))

    def outputday(self):
        if self.formt == "Day" or "day":
            print(self.dyfull[self.day])
        elif self.formt == "Shortday" or "shortday":
            print(self.shortdy[self.day])
        elif self.formt == "Char" or "char":
            print(self.chardy[self.day])
        else: print("No work")

    dat = dateformat()
    dat.getday()
    dat.getformat()
    dat.outputday()
martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

0

Operator precedence matters

Your if statements of the form:

if self.formt == "Day" or "day" are the same as saying if (self.formt == "Day") or (true), with the whole thing evaluating to true always. Either use something like this:

if self.formt.lower() == "day"

or make sure you check for equality twice:

if self.formt == "Day" or self.formt == "day"

Python also has convenience syntax called tuples which is another option:

if self.formt in ("Day", "day")

The referenced question that this is a duplicate of goes into much more detail of why this is the case.

Luke Briggs
  • 3,745
  • 1
  • 14
  • 26