2017-10-14 135 views
1

我是Python3編碼的新手,我在這裏遇到問題。 在第14行中,我打算通過在回答「n」到「再試一次?」的部分打印「Thank you!Goodbye」來結束此程序。然而,事實證明,即使我在其下插入「休息」,我也會重新開始。現在,我唯一能提出的解決方案是用sys.exit(0)結束整個程序,但我不認爲它是一個理想的解決方案,因爲它只是關閉了整個程序。如何結束程序(Python)?

import sys 
while True: 

x=int(input("Enter the coins you expected=")) 
f=int(input("Enter first coin=")) 

while f!=1 and f!=5 and f!=10 and f!=25: 
    print("invalid number") 
    f=int(input("Enter first coin=")) 

if x>f: 
    while x>f: 
     n=input("Enter next coin=") 
     if not n: 
      print("Sorry-you only entered",f,"cents") 
      again=input("Try again (y/n)?=") 
      if again=="y": 
       True 
      elif again=="n": 
       print("Thank you, goodbye!") 
       sys.exit(0) 
      break 

     while int(n)!=1 and int(n)!=5 and int(n)!=10 and int(n)!=25: 
      print("invalid number") 
      n=input("Enter next coin=") 
     f=f+int(n) 
+0

您的問題已回答? – Adi219

+0

是的,我的問題得到解答,它的工作:)! –

回答

1

本替換你的整個代碼:

import sys 

Stay = True 

while Stay: 

    x = int(input("Enter the coins you expected = ")) 
    f = int(input("Enter first coin = ")) 

    while f != 1 and f != 5 and f != 10 and f != 25: 
     f = int(input("Invalid number entered./nEnter first coin = ")) 

    while x > f and Stay: 

     n = input("Enter next coin = ") 

     if not n: 

      print("Sorry, you only entered " + str(f) + " cents") 
      again = input("Try again (y/n)?=") 

      if again == "n": 
       print("Thank you, goodbye!") 
       Stay = False 

     if Stay: 

      n = int(n) 
      while n != 1 and n != 5 and n != 10 and n != 25: 
       print("Invalid number entered.") 
       n = int(input("Enter next coin = ")) 
      f += n 

我做你的代碼更易讀,並通過使用布爾標誌(Stay)固定您的問題。這基本上意味着程序在StayTrue時運行,並且Stay在用戶輸入'n'時變爲False