-2

#class of bank account with withdraw and deposite how do i add a code that tells the customer to enter a valid amount if he enter symbols or unvalid number or character of the deposite or withdraw

enter code here

def __init__(self):
    self.balance=0
    print("Hello Welcome to the Deposit & Withdrawal ATM")

def deposit(self):
    amount=float(input("Enter amount to be Deposited: "))
    self.balance += amount
    print("\n Amount Deposited:",amount)

i want to add a code that if the user enters a unvalid num or Letter here 

def withdraw(self):
    amount = float(input("Enter amount to be Withdrawn: "))
    if self.balance>=amount:
        self.balance-=amount
        print("\n You Withdrew:", amount)
    else:
        print("\n Insufficient balance ")
Eh4413
  • 1

1 Answers1

0

Let's create a function to see if a number is a valid float. There are two main ways that we can do this. Firstly, we can try to parse it and check to see if we get an error, which is not ideal. Otherwise we can use a trick in the playbook. If we remove a single '.' from a string and it is a valid integer then it must have be a valid float or integer previously. This is the ideal method to use.

def CheckValid(string):
    # This also doesn't accept negative numbers, which is ideal
    return string.replace(".", "", 1).isdigit()
def __init__(self):
    self.balance = 0
    print("Hello Welcome to the Deposit & Withdrawal ATM")

def deposit(self):
    user_input = input("Enter amount to be Deposited: ")
    valid = self.CheckValid(user_input)
    if valid:
        amount = float(user_input)
        self.balance += amount
        print("\n Amount Deposited:", amount)
    else:
        # Example
        print("An invalid value was entered. Please try again!")

def withdraw(self):
    user_input = input("Enter amount to be Withdrawn: ")
    valid = self.CheckValid(user_input)
    if valid:
        amount = float(user_input)
        if self.balance >= amount:
            self.balance -= amount
            print("\n You Withdrew:", amount)
        else:
            print("\n Insufficient balance ")
    else:
        # Example
        print("An invalid value was entered. Please try again!")

def CheckValid(self, string):
    return string.replace(".", "", 1).isdigit()

See:

Checking if a string can be converted to float in Python

Larry the Llama
  • 958
  • 3
  • 13