Home > Net >  Why is my code not working properly (it keeps resulting in the same thing)
Why is my code not working properly (it keeps resulting in the same thing)

Time:06-20

My Money Checking code

class MoneyChecker:
type = ""
amount = 100
def checker(self):
    dirty = "The %d %s is a dirty note" % (self.amount, self.type)
    if money1.amount == 200:
        return dirty
    
    clean = "The %d %s is a clean note" % (self.amount, self.type)
    if money2.amount < 200:
        return clean
    else:
        return dirty
money1 = MoneyChecker()
money1.amount = 200
money1.type = "Naira"

money2 = MoneyChecker()
money2.amount = [100][1]
money2.type = "Naira"
print(money1.checker())
print(money2.checker())

The code is supposed to result

                        "The 200 naira is a dirty note"
                        "The 100 naira is a clean note" 

But it keeps bringing

                        "The 200 naira is a dirty note"  
                        "The 100 naira is a dirty note"

CodePudding user response:

Your if statements are the variables of specific instances, you need to use self:

def checker(self):
        dirty = "The %d %s is a dirty note" % (self.amount, self.type)
        if self.amount == 200:
            return dirty
        
        clean = "The %d %s is a clean note" % (self.amount, self.type)
        if self.amount < 200:
            return clean
        else:
            return dirty

Note: You could remove the first if statement since it is effectively included in the second one:

dirty = "The %d %s is a dirty note" % (self.amount, self.type)
clean = "The %d %s is a clean note" % (self.amount, self.type)

if self.amount < 200:
    return clean
else:
    return dirty

CodePudding user response:

You are checking instances of your class that are defined as global variables, which most would consider a big no-no. It's much simpler to check the current instance using self. For example try the following.

class MoneyChecker:
    type = ""
    amount = 100
    dirty = "The %d %s is a dirty note"
    clean = "The %d %s is a clean note"

    def checker(self):
        output = (self.amount, self.type)
        return self.clean % output if self.amount < 200 else self.dirty % output
    

money1 = MoneyChecker()
money1.type = "Naira"
print(money1.checker())


money2 = MoneyChecker()
money2.amount = 200
print(money2.checker())
  • Related