簡體   English   中英

如何捕獲錯誤並返回到循環的開始?

[英]How to trap errors, and go back to start of a loop?

我正在編寫一些允許用戶計算分子質量的代碼,並且在開始時我與一些特定的關鍵字進行了一些用戶交互。 例如,用戶可以輸入“指令”或“開始”,但如果他們輸入其他內容,程序就會結束。 我該如何打印'error, try again' ,然后重新開始?

print ("Welcome to MOLECULAR MASS CALCULATOR \n")
intro=input("Calculate mass of any molecule or element by entering the chemical formula. \n\n If this is your first time, it is recommended you read the instructions before you start. \n Type 'instructions'. Otherwise, type 'start'. \n\n")

while intro.upper() == 'INSTRUCTIONS':
    print ("\n\n Calculate the mass of any molecule or element by entering the chemical formula. \n\n Subscripts are possible; simply type the chemical formula. For e.g., to type the chemical formula of water simply type 'H20'. Only one digit of subscript per element is possible. \n Subscripts with  brackets, and oefficients are not possible. You would have to manually find the mass individually. For e.g., to find the mass of two gallium carbonate molecules '2Ga2(CO3)3', you would have to find the mass of one gallium carbonate molecule, and then multiply it by two. This would require you to first find the mass of one carbonate atom, then multiply by three, then add the mass of two gallium atoms. \n\n Note: If you make an error with typing, the program will terminate and you will have to  start again.")
    intro=''
    intro=input("\n\n Type 'start' to begin. \n\n ")

while intro.upper() == 'START':
    mol=input("\nEnter a molecule:")
    intro=''
#while intro.upper() != 'START' or 'INSTRUCTIONS':
#     print ("\nError, please try again.")
#     intro=''

最簡單的方法是使用while True:循環,該循環將始終重復,並在循環內使用 'break' 控制它以退出循環並在輸入start放入start代碼,否則continue

例如,這將執行您想要的操作:

print("Welcome to MOLECULAR MASS CALCULATOR \n")

intro = input("Introduction.\n Type  'instructions'. Otherwise, "
              "type 'start'. \n\n")

while True:
    if intro.upper() not in ["START", "INSTRUCTIONS"]:
        intro = input("\nError, please try again:")
        continue

    if intro.upper() == 'INSTRUCTIONS':
        print("Instructions")
        intro = input("\n\n Type 'start' to begin. \n\n ")
    elif intro.upper() == 'START':
        break

# 'START' code goes here
mol = input("\nEnter a molecule:")

順便說一句,您注釋掉的代碼:

while intro.upper() != 'START' or 'INSTRUCTIONS'

不會按您的意願工作。 Python 會將其解釋為:

while (intro.upper() != 'START') or ('INSTRUCTIONS')

其中'INSTRUCTIONS' (或任何非空字符串)將始終評估為 True,因此整個語句將始終為 True。 對值列表進行評估的一種有效方法顯示在我的intro.upper() not in ["START", "INSTRUCTIONS"]示例中, intro.upper() not in ["START", "INSTRUCTIONS"] ,它將正確評估您嘗試執行的操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM