首页 > 解决方案 > 代码在最后一次输入时运行,它会关闭窗口,为什么?

问题描述

我正在为我的编码课程编写“ATM”代码。在注销输入之前,我一直在执行我想要的代码。此时它将在显示“成功注销”之前关闭窗口。我对 python 很陌生,所以我不知道这是否正常,或者我的代码中的某些内容是否关闭。我确信有一种更好的方法可以一起编写我的代码,但据我所知,这是我能做的最好的。

funds = 500

while True:
  print("\nMenu Options:\n\n1: Withdraw Money\n2: Deposit Money\n3: View Balance\n4: Logout\n\n") 
  user_input = int(input("Enter Option: "));

  #Withdraw process
  while user_input == 1:
    amount = int(input("\n  Enter Withdraw Amount: $"))
    while amount > funds:
      print("\nInsufficient Funds")
      break
    else:
      funds -= amount
      print("\nSuccessful Withdraw of $", amount)
      break

  #Deposit process
  while user_input == 2:
    amount = int(input("\n  Enter Deposit Amount: $"))
    funds += amount
    print("\nSuccessful Deposit of $", amount)
    break

  #View balance process
  while user_input == 3:
    print("\nAvailable Balance: $",funds)
    break

  #Logout process
  if user_input == 4:
    print("\nSuccessful Logout!")
    break


  #Wrong menu option input process
  while user_input > 4:
    break

标签: pythonpython-3.x

解决方案


打开一个只包含以下语句的文件:

print("Hello world!")

您会注意到 python.exe 几乎立即打开和关闭。这是因为 Python 脚本的工作就是简单地打印“Hello world!”。到控制台。一旦完成,它就没有生意了,所以它退出了。

在您的代码中,只要“成功注销!” 打印后,该break语句将程序流从顶层while True:循环中中断,并且由于没有其他语句要执行,因此它关闭了控制台。

为了解决这个问题,您可以使用input("Press any key to exit.")before your break,这样您就有机会在程序退出之前看到您的输出。

此外,您的代码功能完善!我相信随着你的学习,你会发现更多关于 Python 的东西。比如知道什么时候用什么while break时候用if elif else。但是现在,只要您的代码按照您的指示去做,您就可以开始了!


推荐阅读