2017-04-21 69 views
0

當我學習python時,我創建了這段代碼,但問題是當某人輸入與stm或mts不同的東西時,它只是輸出錯誤信息並停止,我需要它繼續並自行運行代碼,因此我添加了一個while循環與繼續聲明,但它不能正常工作,它只是保持垃圾郵件的錯誤信息,請任何想法如何使我的代碼保持運行沒有垃圾郵件的信息或停止後..非常感謝你!如何在發生錯誤時讓程序繼續/重新啓動?

下面的代碼:

print("Welcome to MoroccanDirham_SaudiRiyal converter program!") 

def mConv(): 
    def rial_saudi_to_moroccan_dirham(sar): 
     amount = sar * 2.67 
     print("Here is the result: ", amount, "MAD") 

    def moroccan_dirham_to_rial_saudi(mad): 
     amount = mad * 0.37 
     print("Here is the result: ", amount, "SAR") 
    usChoice = str(input("For SAR to MAD type stm and for MAD to SAR type mts: ")) 

    while True: 
     if usChoice == str("stm"): 
      x = int(input("Type the amount of money you want to convert: ")) 
      rial_saudi_to_moroccan_dirham(x) 
      return False 
     elif usChoice == str("mts"): 
      y = int(input("Type the amount of money you want to convert: ")) 
      moroccan_dirham_to_rial_saudi(y) 
      return False 
     elif usChoice != str("stm") or usChoice != str("mts") : 
      print("Error! Please choose between stm and mts.") 
      continue 
      return False 
     else: 
      return True 
mConv() 

回答

0

移動usChoice = STR(輸入( 「對於特區MAD型STM和MAD到SAR型MTS:」)) while循環中,並刪除你的最後別的聲明中,你不應該放回到那裏,你可以寫一個錯誤信息

打印(「歡迎來到MoroccanDirham_SaudiRiyal轉換程序!」)

def mConv(): 
    def rial_saudi_to_moroccan_dirham(sar): 
     amount = sar * 2.67 
     print("Here is the result: ", amount, "MAD") 

    def moroccan_dirham_to_rial_saudi(mad): 
     amount = mad * 0.37 
     print("Here is the result: ", amount, "SAR") 


    while True: 
     usChoice = str(input("For SAR to MAD type stm and for MAD to SAR type mts: ")) 
     if usChoice == str("stm"): 
      x = int(input("Type the amount of money you want to convert: ")) 
      rial_saudi_to_moroccan_dirham(x) 
      return False 
     elif usChoice == str("mts"): 
      y = int(input("Type the amount of money you want to convert: ")) 
      moroccan_dirham_to_rial_saudi(y) 
      return False 
     else: 
      print("Invalid choice. Allowed choices"); 
      print("stm - rial to dirham"); 
      print("mts - dirham to rial"); 
mConv() 
+1

太謝謝你了它的工作原理,我應該把usChoice = str(輸入(「SAR for MAD type stm和MAD to SAR type mts:」))放在while循環中,就像你告訴我的,我真的沒有注意到它,但我確實知道我的代碼應該在每次與之前的2次沒有太大關係時重新獲得其他變量,您清除了很多錯誤先生,我非常感謝! –

相關問題