Python 程序,如何使 atm 程序循环

Python program, how to make an atm program loop

如何让它在执行此操作后循环回到开头?每笔交易结束后,不再回头看是否可以选择其他选项。 谢谢,非常感谢。

balance=7.52
print("Hi, Welcome to the Atm.")
print("no need for pin numbers, we already know who you are")
print("please selection one of the options given beneath")
print("""
    D = Deposit
    W = Withdrawal
    T = Transfer
    B = Balance check
    Q = Quick cash of 20$
    E = Exit
    Please select in the next line.   
""")
option=input("which option would you like?:")
if option==("D"):
    print("How much would you like to deposit?")
    amount=(int(input("amount:")))
    total=amount+balance
elif option ==("W"):
    print("How much would you like to withdrawl?")
    withdrawl=int(input("how much would you like to take out:?"))
    if balance<withdrawl:
        print("Error, insufficent funds")
        print("please try again")
elif option == "T":
    print("don't worry about the technicalities, we already know who you're          transferring to")
    transfer =int(input("How much would you like to transfer:?"))
    print("you now have", balance-transfer,"dollars in your bank")
elif option=="B":
    print("you currently have",balance,"dollars.")
elif option=="Q":
    print("processing transaction, please await approval")
    quicky=balance-20
    if balance<quicky:
         print("processing transaction, please await approval")
    print("Error, You're broke.:(")
elif option=="E":
      print("Thanks for checking with the Atm")
      print("press the enter key to exit")

您似乎在询问带有 sentinel value 的循环。

在打印菜单之前的某处,设置一个标记值:

keep_going = True

然后,最好在下一行(在打印循环时你想看到的第一件事之前)开始循环。

while keep_going:   # loop until keep_going == False

正如所写,这是一个无限循环。 while 语句下方缩进块中的所有内容都将按顺序永远重复。这显然不是我们想要的——我们必须有办法出去,这样我们才能用我们的电脑做其他事情!这就是我们的哨兵进来的地方。

内置一个新的菜单选项以允许用户退出。假设您将其键入 "Q",然后用户选择了它。然后,在该分支中:

elif option == 'Q':
    keep_going = False

由于该分支中只有这些,我们 "fall off" 循环的底部,然后返回到 while 语句,该语句现在无法通过检查。循环终止!

顺便说一下,您应该考虑阅读 The Python Style Guide. It's very easy to read and gives you an idea how to make your code also very easy to read. Most every Python programmer abides by it and expects others to do the same, so you should too! If you want help learning it, or aren't sure if you're doing it right, there are tools to check your code 以帮助您保持整洁和无错误。

编程愉快!