Question

PYTHON The provided code in the ATM program is incomplete. Complete the run method of the...

PYTHON

The provided code in the ATM program is incomplete. Complete the run method of the ATM class. The program should display a message that the police will be called after a user has had three successive failures. The program should also shut down the bank when this happens. [comment]: <> (The ATM program allows a user an indefinite number of attempts to log in. Fix the program so that it displays a message that the police will be called after a user has had three successive failures. The program should also shut down the bank when this happens.)

-------------------------------------------------

Atm.py

"""
File: atm.py
Project 8.4

This module defines the ATM class and its application.

Modifies the user interface so that it prints a message and shuts down
if the user fails at three consecutive logins.

Can be modified to run as a script after a bank has been saved.
"""
from bank import Bank, SavingsAccount

class ATM(object):
"""This class represents terminal-based ATM transactions."""

def __init__(self, bank):
self._account = None
self._bank = bank
self._methods = {} # Jump table for commands
self._methods["1"] = self._getBalance
self._methods["2"] = self._deposit
self._methods["3"] = self._withdraw
self._methods["4"] = self._quit

def run(self):
"""Logs in users and processes their accounts."""
failureCount = 0
while True:
# Prompt user to enter name

# Prompt user to enter PIN

# Load account

# If account was not found
# Print "Error, unrecognized PIN"

# If account name does not match name
# Print "Error, unrecognized name"

# If account is valid
# Load account menu


# If an invalid entry was made three times
# Print "Shutting down and calling the cops!" and end program

def _processAccount(self):
"""A menu-driven command processor for a user."""
while True:
print("1 View your balance")
print("2 Make a deposit")
print("3 Make a withdrawal")
print("4 Quit\n")
number = input("Enter a number: ")
theMethod = self._methods.get(number, None)
if theMethod == None:
print("Unrecognized number")
else:
theMethod()
if self._account == None:
break

def _getBalance(self):
print("Your balance is $", self._account.getBalance())

def _deposit(self):
amount = float(input("Enter the amount to deposit: "))
self._account.deposit(amount)

def _withdraw(self):
amount = float(input("Enter the amount to withdraw: "))
message = self._account.withdraw(amount)
if message:
print(message)

def _quit(self):
self._bank.save()
self._account = None
print("Have a nice day!")

# Top-level functions
def main():
"""Instantiate an ATM and run it."""
bank = Bank("bank.dat")
atm = ATM(bank)
atm.run()

def createBank(number = 0):
"""Saves a bank with the specified number of accounts.
Used during testing."""
bank = Bank()
for i in range(number):
bank.add(SavingsAccount('Name' + str(i + 1),
str(1000 + i),
100.00))
bank.save("bank.dat")


# Creates a bank with the following names / PINS:
# Name1, 1000
# Name2, 1001
# Name3, 1002
# Name4, 1003
# Name5, 1004
createBank(5)
main()

------------------------------------------------

bank.py

"""
File: bank.py

This module defines the SavingsAccount and Bank classes.
"""
import pickle

class SavingsAccount(object):
"""This class represents a savings account
with the owner's name, PIN, and balance."""

RATE = 0.02
  
def __init__(self, name, pin, balance = 0.0):
self._name = name
self._pin = pin
self._balance = balance

def __str__(self):
result = 'Name: ' + self._name + '\n'
result += 'PIN: ' + self._pin + '\n'
result += 'Balance: ' + str(self._balance)
return result

def getBalance(self):
return self._balance

def getName(self):
return self._name

def getPin(self):
return self._pin

def deposit(self, amount):
"""Deposits the given amount."""
self._balance += amount
return self._balance

def withdraw(self, amount):
"""Withdraws the given amount.
Returns None if successful, or an
error message if unsuccessful."""
if amount < 0:
return 'Amount must be >= 0'
elif self._balance < amount:
return 'Insufficient funds'
else:
self._balance -= amount
return None

def computeInterest(self):
"""Computes, deposits, and returns the interest."""
interest = self._balance * SavingsAccount.RATE
self.deposit(interest)
return interest

class Bank(object):
"""This class represents a bank as a dictionary of
accounts. An optional file name is also associated
with the bank, to allow transfer of accounts to and
from permanent file storage."""

def __init__(self, fileName = None):
"""Creates a new dictionary to hold the accounts.
If a file name is provided, loads the accounts from
a file of pickled accounts."""
self._accounts = {}
self.fileName = fileName
if fileName != None:
fileObj = open(fileName, 'rb')
while True:
try:
account = pickle.load(fileObj)
self.add(account)
except EOFError:
fileObj.close()
break

def add(self, account):
"""Inserts an account using its PIN as a key."""
self._accounts[account.getPin()] = account

def remove(self, pin):
return self._accounts.pop(pin)

def get(self, pin):
return self._accounts.get(pin, None)

def computeInterest(self):
"""Computes interest for each account and
returns the total."""
total = 0
for account in self._accounts.values():
total += account.computeInterest()
return total

def __str__(self):
"""Return the string rep of the entire bank."""
return '\n'.join(map(str, self._accounts.values()))

def save(self, fileName = None):
"""Saves pickled accounts to a file. The parameter
allows the user to change file names."""
if fileName != None:
self.fileName = fileName
elif self.fileName == None:
return
fileObj = open(self.fileName, 'wb')
for account in self._accounts.values():
pickle.dump(account, fileObj)
fileObj.close()
  
def testBank(number = 0):
"""Returns a bank with the specified number of accounts and/or
the accounts loaded from the specified file name."""
bank = Bank()
for i in xrange(number):
bank.add(SavingsAccount('Name' + str(i + 1),
str(1000 + i),
100.00))
return bank

0 0
Add a comment Improve this question Transcribed image text
Answer #1
#i have provided implementation of the required function only
def run(self):

    """Logs in users and processes their accounts."""

    failureCount = 0
    while True:
        name = input('Enter account name: ')
        pin = input('Enter pin: ')
        acc = self._bank.get(pin)
        if acc is None:
            print("Error, unrecognized PIN")
            failureCount+=1
        else:
            if acc._name!=name:
                print('Error, unrecognised name')
                failureCount+=1
            else:
                self._account=acc
                self._processAccount()
                failureCount=0
        if failureCount==3:
            print('Shutting down and calling the cops')
            break

Add a comment
Know the answer?
Add Answer to:
PYTHON The provided code in the ATM program is incomplete. Complete the run method of the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I am trying to create a ATM style bank program that accept the customer id ,...

    I am trying to create a ATM style bank program that accept the customer id , in the welcoming panel ,but how do i make when the customer input their id# and click on the ok button then they have 3 or so tries to input the correct id# and if successful then send to the other panel where they choose which transaction to they want to make for example savings , checking account , make and deposit , and...

  • The program needs to be in python : First, create a BankAccount class. Your class should...

    The program needs to be in python : First, create a BankAccount class. Your class should support the following methods: class BankAccount (object): """Bank Account protected by a pin number.""" def (self, pin) : init "n"Initial account balance is 0 and pin is 'pin'."" self.balance - 0 self.pin pin def deposit (self, pin, amount): """Increment account balance by amount and return new balance.""" def withdraw (self, pin, amount): """Decrement account balance by amount and return amount withdrawn.""" def get balance...

  • If the employee is a supervisor calculate her paycheck as her yearly salary / 52 (weekly...

    If the employee is a supervisor calculate her paycheck as her yearly salary / 52 (weekly pay) If the employee is not a supervisor and she worked 40 hours or less calculate her paycheck as her hourly wage * hours worked (regular pay) If the employee is not a supervisor and worked more than 40 hours calculate her paycheck as her (hourly wage * 40 ) + (1 ½ times here hourly wage * her hours worked over 40) (overtime...

  • Zybooks 11.12 LAB*: Program: Online shopping cart (continued) Python 3 is the code needed and this...

    Zybooks 11.12 LAB*: Program: Online shopping cart (continued) Python 3 is the code needed and this is in Zybooks Existing Code # Type code for classes here class ItemToPurchase: def __init__(self, item_name="none", item_price=0, item_quantity=0): self.item_name = item_name self.item_price = item_price self.item_quantity = item_quantity # def __mul__(self): # print_item_cost = (self.item_quantity * self.item_price) # return '{} {} @ ${} = ${}' .format(self_item_name, self.item_quantity, self.item_price, print_item_cost) def print_item_cost(self): self.print_cost = (self.item_quantity * self.item_price) print(('{} {} @ ${} = ${}') .format(self.item_name, self.item_quantity, self.item_price,...

  • 9c Python 1) What is the output of the following code? Refer to the Weapon, Blaster,...

    9c Python 1) What is the output of the following code? Refer to the Weapon, Blaster, and Bowcaster classes. File 1: weapon.py class Weapon: def init ( self, power ): self.mPower = power return Example: import blaster from bowcaster import Bowcaster def getPower( self ): return self.mPower han = blaster.Blaster( 8000, 20 ) print("HP:", han.getPower( ) ) print( "HR:", han.getFireRate()) chewie = Bowcaster( 3000, 6) print( "CB:", chewie.getBarrelSize()) print( "CR:", chewie.getRange()) File 2: blaster.py import weapon class Blaster( weapon. Weapon):...

  • PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please...

    PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please so I can understand LinkedList ADT: class myLinkedList:     def __init__(self):         self.__head = None         self.__tail = None         self.__size = 0     def insert(self, i, data):         if self.isEmpty():             self.__head = listNode(data)             self.__tail = self.__head         elif i <= 0:             self.__head = listNode(data, self.__head)         elif i >= self.__size:             self.__tail.setNext(listNode(data))             self.__tail = self.__tail.getNext()         else:             current = self.__getIthNode(i - 1)             current.setNext(listNode(data,...

  • Complete the function load_trees_from_file() specified in A1.py It should take as a parameter the name of...

    Complete the function load_trees_from_file() specified in A1.py It should take as a parameter the name of a file containing a set of trees and return a list containing instances of the Tree class representing all of the trees listed in the file. If the file does not exist, it should print that the file is not found and return None. You will need to include your Tree class definition from Question 1 in your answer. Consider the following code fragment:...

  • PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment...

    PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment the lines please so I can understand. There are short and med files lengths for each the list of names/ids and then search id file. These are the input files: https://codeshare.io/aVQd46 https://codeshare.io/5M3XnR https://codeshare.io/2W684E https://codeshare.io/5RJwZ4 LinkedList ADT to store student records(code is below). Using LinkedList ADT instead of the Python List. You will need to use the Student ADT(code is below) Imports the Student class...

  • Python only please, thanks in advance. Type up the GeometricObject class (code given on the back...

    Python only please, thanks in advance. Type up the GeometricObject class (code given on the back of the paper). Name this file GeometricObjectClass and store it in the folder you made (xxlab14) 1. Design a class named Rectangle as a subclass of the GeometricObject class. Name the file RectangleClass and place it in the folder. 2. The Rectangle class contains Two float data fields named length and width A constructor that creates a rectangle with the specified fields with default...

  • I am currently facing a problem with my python program which i have pasted below where...

    I am currently facing a problem with my python program which i have pasted below where i have to design and implement python classes and record zoo database and takes user input as query. the error i am recieving says that in line 61 list index is out of range. kindly someone help me with it as soon as possible. Below is the program kindly check and correct it. Thanks! class Animal: def __init__(self, name, types, species, mass): self.name=name self.type=types...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT