Python -初学者ATM项目

tzxcd3kk  于 2022-12-05  发布在  Python
关注(0)|答案(1)|浏览(155)

我希望它,使我目前的余额将作为下一个循环提取的金额。
输入密码:123 1 -余额查询2 -取款3 -存款X -退出输入您的选择:2嗨姓名1.

您当前余额为50000

输入要提取的金额:400交易成功

您当前的余额为49600

输入密码:123 1 -余额查询2 -取款3 -存款X -退出输入您的选择:2嗨姓名1.

您当前的余额是50000***问题***

输入要提取的金额:
这是目前我的代码。(抱歉混乱的代码,因为我是一个初学者)

pin = [123, 456, 789]
balance = [50000, 2000, 500]
name = ["name1", "name2", "name3"]

def main():
    while True:
        pin_input = input('Enter pin:')
        try:
            n = int(pin_input)
        except:
            break
        if n in pin:
            print('1 – Balance Inquiry')
            print('2 – Withdraw')
            print('3 – Deposit')
            print('X – Exit')
            choice = input('Enter your choice:')
            c = int(choice)
            if choice == 'X':
                print('Thank you for banking with us!')
                break
            else:
                pol = pin.index(n)
                if c == 1:
                    print(f'Hi {name[pol]}.')
                    print(f'Your current balance is {balance[pol]} ')
                elif c == 2:
                    print(f'Hi {name[pol]}.')
                    print(f'Your current balance is {balance[pol]} ')
                    withdraw = int(input('Enter amount to withdraw: '))
                    if withdraw > balance[pol]:
                        print('Not enough amount')
                    else:
                        difference = balance[pol] - withdraw
                        print('Transaction Successful')
                        print(f'Your current balance is {difference}')
                elif c == 3:
                    print(f'Hi {name[pol]}.')
                    print(f'Your current balance is {balance[pol]} ')
                    deposit = int(input('Enter amount to deposit: '))
                    sums = deposit + balance[pol]
                    print('')
                    print(f'Your current balance is {sums}')

main()
lymnna71

lymnna711#

欢迎使用Python。我知道你的问题是什么了。当你处理撤销时,你创建了一个新的变量,并执行了减法,你只是显示了新的结果,而没有更新它。所以要解决这个问题,你需要替换下面的代码:

difference = balance[pol] - withdraw
print(f'Transaction Successful.\nYour current balance is {difference}')

与:

balance[pol] -= withdraw
print(f'Transaction Successful.\nYour current balance is {balance[pol]}')

我冒昧地编辑了你的代码,使它更“专业”,但也使你可以阅读和理解它(我添加了评论,让你阅读)。

pin = [123, 456, 789]
balance = [50000, 2000, 500]
name = ["name1", "name2", "name3"]

def main():
    while True:
        try:
            pin_input = int(input('Enter pin:'))
        except ValueError: #It's bad practice to leave it just as "except".
            break
        if pin_input in pin:
            print('1 – Balance Inquiry')
            print('2 – Withdraw')
            print('3 – Deposit')
            print('X – Exit')
            choice = input('Enter your choice:')
            #As you can see, I have removed the conversion because no one will care if it is int or str, it's happening behind the scene.
            if choice == 'X':
                print('Thank you for banking with us!')
                break
            #You don't need the else statement because if the choice would be 'X' it would automatically exit.
            pol = pin.index(pin_input)
            if choice == '1':
                print(f'Hi {name[pol]}.\nYour current balance is {balance[pol]}') #Using \n to downline instead of using two prints.
            elif choice == '2':
                print(f'Hi {name[pol]}.\nYour current balance is {balance[pol]}') #Using \n to downline instead of using two prints.
                withdraw = int(input('Enter amount to withdraw: ')) #Assuming the user will write an integer. 
                if withdraw > balance[pol]:
                    print('Not enough amount')
                    break # Let's just add that here (easier to read) and we don't need the else statement anymore. 
                balance[pol] -= withdraw
                print(f'Transaction Successful.\nYour current balance is {balance[pol]}')
            elif choice == '3':
                print(f'Hi {name[pol]}.\nYour current balance is {balance[pol]}')#Using \n to downline instead of using two prints.
                deposit = int(input('Enter amount to deposit: ')) #Assuming the user will write an integer.  the user 
                sums = deposit + balance[pol]
                print(f'\nYour current balance is {sums}') #\n instead of a whole print function. 
   if __name__ == "__main__": #Use this script as the main script. 
       main()

"干得好,继续干下去!"
另外,我想添加我自己的创建ATM机的方法。我希望有一天当你学习并有更多的知识时,你会再次打开这个并尝试理解它。(这个代码只在py-3.10或更高版本中工作)

代码:

class ATM:
    def __init__(self, pin) -> None:
        self.pin = pin

    def Balance(self) -> str:
        return f"{data[self.pin][1]}, Your balance is: {data[self.pin][0]}"

    def Withdraw(self) -> str:
        try:
            withdraw = int(input('Enter amount to withdraw: '))
            if withdraw > data[self.pin][0]:
                return f"{data[self.pin][1]}, Looks like you can't withdraw {withdraw}$ due to lower balance.\nYou can withdraw up to {data[self.pin][0]}$."
            data[self.pin][0] -= withdraw
        except ValueError:
            return f"{data[self.pin][1]}, Looks like there was an error with your request to withdraw. Please try again."

        return f"{data[self.pin][1]}, You've successfully withdrawn {withdraw}$. Your remaining balance is: {data[self.pin][0]}$."

    def Deposit(self) -> str:
        try:
            deposit = int(input('Enter amount to Deposit: '))
            data[self.pin][0] += deposit
        except ValueError:
            return f"{data[self.pin][1]}, Looks like there was an error with your request to deposit. Please try again."

        return f"{data[self.pin][1]}, You've deposited {deposit}$ into your account. Your balance right now is {data[self.pin][0]}"

if __name__ == "__main__":
    data = {
        123 : [50000, "name1"],
        456 : [2000, "name2"],
        789 : [500, "name3"]
    }

    options = {
        1 : "Balance Inquiry",
        2 : "Withdraw",
        3 : "Deposit",
        'X' : "Exit"
    }

    running = True

    while running:
        try:
            pin = int(input("Enter your pin: "))
            if pin in data:
                user = ATM(pin)
            else:
                print(f"User {pin} Doesn't exist. Please check your input and try again.")
                continue
            for key, value in options.items():
                print(f"Press '{key}' for {value}")
            while True:
                action = input("Please enter your action: ")
                match action:
                    case '1':
                        print(user.Balance())
                        break
                    case '2':
                        print(user.Withdraw())
                        break
                    case '3':
                        print(user.Deposit())
                        break
                    case 'X' | 'x':
                        running = False
                        break
                    case _:
                        print("This action doesn't exist. Please try again.")
                        continue
        except ValueError:
            print("There is an error in the given pin. Please try again.")
            continue

相关问题