techrawther
techrawther

Reputation: 183

Python Newbie Questions - Not printing correct values

I am newbie to python and I doing doing some OOPS concept exploring in Python.

Following is my Account class:

class Account:
    def __init__(self,balance):
        self.__balance=int(balance)

    def deposit(self,deposit_amt):
        self.__balance=self.__balance + int(deposit_amt)

    def withdraw(self,withdraw_amt):
        withdraw_amt=int(withdraw_amt)
        self.__balance=self.__balance -- int(withdraw_amt)
        print(self.__balance)
        print("Subtracting" + str(withdraw_amt))

    def get___balance(self):
        return(self.__balance)

    def __str__(self):
        return("The Balance in the Account is " + str(self.get___balance()))

The account_test program:

import account
def main():
    balance_amt = input("Enter the balance amount \t")
    new_account=account.Account(int(balance_amt))


    deposit_amt=input("Enter the Deposit Amount \t")
    new_account.deposit(deposit_amt)
    print(new_account)

    withdraw_amt=input("Enter the Withdraw Amount \t")
    new_account.withdraw(withdraw_amt)
    print(new_account)


main()

But I am getting the wrong output:

Enter the balance amount    3000
Enter the Deposit Amount    400
The Balance in the Account is 3400
Enter the Withdraw Amount   300
3700
Subtracting 300
The Balance in the Account is 3700

When I do withdraw I am getting the amount added instead of subtracted. What am I doing wrong here?

Since I am newbie, I need some suggestion in my programming practice. Is my coding style appropriate?

Upvotes: 1

Views: 283

Answers (2)

chown
chown

Reputation: 52738

With the double -- (negative) you are subtracting a negative value (i.e. adding a positive value).
A more clear explanation would look like:

self.__balance = self.__balance - (0 - int(withdraw_amt))

Therefore, change this:

self.__balance=self.__balance -- int(withdraw_amt)

To this:

self.__balance=self.__balance - int(withdraw_amt)

Or better yet, to this:

self.__balance -= int(withdraw_amt)

Upvotes: 2

Foo Bah
Foo Bah

Reputation: 26271

self.__balance=self.__balance -- int(withdraw_amt)

is actually parsed as

self.__balance=self.__balance - (- int(withdraw_amt))

which is to say, it is adding the withdraw amount. try with a single -

Upvotes: 1

Related Questions