在基于“ ATM”的程序中使用什么方法

时间:2018-12-03 22:23:37

标签: python pseudocode

我从分配ATM代码开始,应该以某种方式使用文本文件。到目前为止,我已经知道了:

print("Hello, and welcome to the ATM machine!\n")

a_pin = {1111, 2222, 3333, 4444}

def process():
    pin = int(input("\nplease enter below your 4-digit pin number: "))
    if pin in a_pin:
        if pin == (1111):
            f = open("a.txt", "r")
        elif pin == (2222):
            f = open("b.txt", "r")
        elif pin == (3333):
            f = open("c.txt", "r")
        elif pin == (4444):
            f = open("d.txt", "r")
        print(
    """
        MENU:
        1: view your current balance
        2: make a withdraw
        3: make a deposit
        4: exit

     """)

        option = input("\nwhat would you like to do? ")

        if option == "1":
            print(f.read())
        elif option == "2":
            y = str(input("\nHow much would you like you like to withdraw? "))
            f.write(y)
            print("Excellent, your transaction is complete!")
        elif option == "3":
            z = str(input("\nHow much would you like to deposit? "))
            f.write(z)
            print("Excellent, your transaction is complete!")
        elif option == "4":
            input("Please press the enter key to exit.")



    else:
        print("\nthat was a wrong pin number!")
        x = input("\nwould you like to try again? '(y/n)' ")
        if x == "y":
            process()
        else:
            input("\npress the enter key to exit.")

process()

该代码目前可以使用,但是我想通过询问如何在撤回/存款时最有效地覆盖文本文件上的内容来节省一些时间。 我正在考虑腌制的文件...但是对于任何建议都会非常高兴,因为如果我想在撤回/存款后向用户显示新的金额,那么像write这样的普通命令就无法真正完成此任务。 非常感谢!

2 个答案:

答案 0 :(得分:0)

关键是要考虑打开文件所需的“模式”,以便不仅可以(r)读取文件,还可以(r+)对其进行修改:

if pin == (1111):
        f = open("a.txt", "r+")
    elif pin == (2222):
        f = open("b.txt", "r+")
    elif pin == (3333):
        f = open("c.txt", "r+")
    elif pin == (4444):
        f = open("d.txt", "r+")

然后将当前余额存储在文件中,并在每次交易后更新。

# read current balance from file and save its value
bal = float(f.read().strip('\n'))  # or replace float() with int()

# reset file pointer to beginning of file before updating contents
f.seek(0)

if option == '1':
    print(f.read()) # or simply, print(bal)
elif option == '2':
    y = str(input("\nHow much would you like you like to withdraw? "))
    bal -= int(y)            # calculate new balance
    f.write(str(bal)+'\n')   # write new balance to file as a string
    print("Excellent, your transaction is complete!")
elif option == '3':
    z = str(input("\nHow much would you like to deposit? "))
    bal += int(z)
    f.write(str(bal)+'\n')
    print("Excellent, your transaction is complete!")

答案 1 :(得分:0)

如果仅保留最新余额,请尝试以w +模式打开文本文件,读取整行并将值保留在程序中,然后根据需要对其进行修改,最后写入最终值并添加结尾行。如果应该在每次运行程序时更新该值。