Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Code seems to access lists it's not meant to

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()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading