簡體   English   中英

對於異常程序,如果您沒有獲得所需的輸出,如何在使用 Python 最多 3 次嘗試后退出程序?

[英]How to exit the program after max 3 attempts using Python, for exception program , if you dont get the desired output?

對於異常程序,如果您沒有獲得所需的輸出,如何在使用 Python 最多 3 次嘗試后退出程序?

while True:
         try:
            x = int(input("Please enter a number: "))
            break
         #except Exception as e:
         #     print (e)
         except ValueError:
             print ("You have entered the non-numeric value. Enter the numerical value.")
         except KeyboardInterrupt:
             print ("\nYou have press Ctr+C.")
             exit (1)
nothing = 0
while nothing < 3:
    nothing += 1
    try:
       x = int(input("Please enter a number: "))
       break
         #except Exception as e:
         #     print (e)
    except ValueError:
        print ("You have entered the non-numeric value. Enter the numerical value.")
    except KeyboardInterrupt:
        print ("\nYou have press Ctr+C.")
        break

嘗試:

c = 0
while c < 3:
     c += 1
     try:
        x = int(input("Please enter a number: "))
        break
     except ValueError:
         print ("You have entered the non-numeric value. Enter the numerical value.")
     except KeyboardInterrupt:
         print ("\nYou have press Ctr+C.")
         break

您想在 3 次嘗試后退出。 試試這個並計算輸入是錯誤的:

num_err = 0
while num_err < 3:
    try:
        x = int(input("Please enter a number: "))
    except ValueError:
        print ("You have entered the non-numeric value. Enter the numerical value.")
        num_err += 1
    except KeyboardInterrupt:
        print ("\nYou have press Ctr+C.")
        break

使用sys.exit()停止整個腳本

import sys

while True:
     try:
        x = int(input("Please enter a number: "))
     #except Exception as e:
     #     print (e)
     except ValueError:
         print ("You have entered the non-numeric value. Enter the numerical value.")
     except KeyboardInterrupt:
         print ("\nYou have press Ctr+C.")
         sys.exit()

我閱讀了上面提交的所有代碼,但缺少一件事,如果用戶enter兩個錯誤的值,然后enter一個正確的值,他只有一次機會。 也就是說,如果用戶在輸入兩個正確的inputenter任何錯誤的input ,則循環將中斷。

所以我試圖解決這個問題。 看我的代碼...

count = 0
while True:
    try:
        x = int(input("Please enter a number: "))
        count = 0
        break
    except ValueError:
        count += 1
        print("You have entered the non-numeric value.Only three invalid inputs are allowed. Enter the numerical value.")

    except KeyboardInterrupt:
        print("\nYou have press Ctr+C.")
        exit(1)
    if count == 3:
        break

我試圖解釋我在這段code中寫的內容。 正如您所提到的,用戶只能enter三個invalid input ,因此每次user enter invalid input時,我都會增加variable count 但如果user enter有效input ,則count將為0 這意味着user最多可以enter三個invalid input 連續entering三個invalid inputcount3loop break

暫無
暫無

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

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