Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Create a Class to Simulate a Bank Account Supporting Deposits, Withdrawals and Balance Inquiries

Python Create a Class to Simulate a Bank Account Supporting Deposits, Withdrawals and Balance Inquiries

Document Object Reference Manual Python3 Examples

We will create a class named BankAccount class to simulate the basic operations of a bank account. The class will include deposits, withdrawals and balance inquiries. We will use instance variables to store the account balance and provide methods to operate on them.

Example

class

BankAccount:

   

def

init

(

self

,

owner

,

balance

=

0

)

:

       

self

.

owner

=

owner

       

self

.

balance

=

balance

   

def

deposit

(

self

,

amount

)

:

       

if

amount >

;

0

:

           

self

.

balance

=

amount

           

print

(

f

"Deposited {amount}. New balance is {self.balance}."

)

       

else

:

           

print

(

"Deposit amount must be positive."

)

   

def

withdraw

(

self

,

amount

)

:

       

if

amount >

;

self

.

balance

:

           

print

(

"Insufficient funds."

)

       

elif

amount <

;=

0

:

           

print

(

"

;

Withdrawal amount must be positive."

;

)

       

else

:

           

self

.

balance

=

amount

           

print

(

f"

;

Withdrew

{

amount

}

.

New

balance

is

{

self

.

balance

}

."

;

)

   

def

get_balance

(

self

)

:

       

return

self

.

balance

Example usage

account

=

BankAccount

(

"

;

John Doe"

;,

100

)

account.

deposit

(

50

)

account.

withdraw

(

20

)

print

(

f"

;

Current balance:

{

account.

get_balance

(

)

}

"

;

)

Code analysis:

Output result:

Deposited 50. New balance is 150.
Withdrew 20. New balance is 130.
Current balance: 130

Document Object Reference Manual Python3 Examples