30. Problem to create a class in Python

In this Python oops program, we will create a class in Python. A class called BankAccount with attributes account_number and balance. Include methods to deposit and withdraw money from the account.

Create a class in Python

Steps to solve the program
  1. The BankAccount class has a constructor method __init__ that takes two parameters, account_number and balance. It initializes the instance variables self.account_number and self.balance with the provided values.
  2. The deposit method allows depositing money into the account. It takes an amount parameter and increases the account’s balance by that amount. It then prints a success message along with the new balance.
  3. The withdraw method allows withdrawing money from the account. It takes an amount parameter and checks if the account balance is sufficient to cover the requested withdrawal amount. If so, it deducts the amount from the balance and prints a success message with the new balance. If the account balance is insufficient, it prints a message indicating the withdrawal is denied.
  4. An object of the BankAccount class is created with an account number of “1234567890” and an initial balance of 1000. The account variable refers to this object. The deposit method is called on the account object with an amount of 500, which increases the balance to 1500 and prints a success message.
  5. Then, the withdraw method is called with an amount of 2000, which is higher than the available balance. It prints an insufficient funds message indicating that the withdrawal is denied.

				
					class BankAccount:
    def __init__(self, account_number, balance):
        self.account_number = account_number
        self.balance = balance
    
    def deposit(self, amount):
        self.balance += amount
        print("Deposit of", amount, "successful. New balance:", self.balance)
    
    def withdraw(self, amount):
        if self.balance >= amount:
            self.balance -= amount
            print("Withdrawal of", amount, "successful. New balance:", self.balance)
        else:
            print("Insufficient funds. Withdrawal denied.")

# Create an object of the BankAccount class
account = BankAccount("1234567890", 1000)
account.deposit(500)
account.withdraw(2000)
				
			

Output:

				
					Deposit of 500 successful. New balance: 1500
Insufficient funds. Withdrawal denied.
				
			

Related Articles

Create a Python class called Cat that inherits from the Animal class.

Create a Python class called SavingsAccount that inherits from the BankAccount class.

Leave a Comment