如何使用Python在最多3次嘗試后退出程式,對于例外程式,如果你沒有得到想要的輸出?
while True:
try:
x = int(input("請輸入一個數字:"))
break
#except Exception as e: 例外。
# print (e)
except ValueError:
print ("你輸入了非數字值。請輸入數字值。")
except KeyboardInterrupt:
print ("
你已經按了Ctr C。")
exit (1)
uj5u.com熱心網友回復:
nothing = 0。
while nothing < 3:
try:
x = int(input("請輸入一個數字:"))
break
#except Exception as e: 例外。
# print (e)
except ValueError:
print ("你輸入了非數字值。請輸入數字值。")
except KeyboardInterrupt:
print ("
你已經按了Ctr C。")
break
uj5u.com熱心網友回復:
你想在3次嘗試后退出。試試這個,算算輸入是錯誤的:
num_err = 0。
while num_err < 3:
try:
x = int(input("請輸入一個數字:"))
except ValueError:
print ("你輸入了非數字值。請輸入數字值。")
num_err = 1 ("您輸入的是非數字值")
except KeyboardInterrupt:
print ("
你已經按了Ctr C。")
break
uj5u.com熱心網友回復:
嘗試:
c = 0
while c < 3:
c = 1 3: c = 1
try:
x = int(input("請輸入一個數字:"))
break
except ValueError:
print ("You have entered the non-numeric value. 請輸入數字值。")
except KeyboardInterrupt:
print ("
你已經按了Ctr C。")
break
uj5u.com熱心網友回復:
使用sys.exit()來停止整個腳本
import sys
while True:
try:
x = int(input("請輸入一個數字:"))
#except Exception as e:
# print (e)
except ValueError:
print ("你輸入了非數字值。請輸入數字值。")
except KeyboardInterrupt:
print ("
你已經按了Ctr C。")
sys.exit()
uj5u.com熱心網友回復:
我讀了上面提交的所有代碼,但缺少一件事,如果一個用戶
輸入兩個錯誤的值,然后輸入一個正確的值,之后他只有一次機會。也就是說,如果用戶在輸入兩個正確的input后,input再輸入任何錯誤的input,回圈就會中斷。
所以我試圖解決這個問題。看看我的代碼...
count = 0。
while True:
try:
x = int(input("請輸入一個數字:"))
count =0
break
except ValueError:
count = 1
print("You have entered the non-numeric value.Only three invalid inputs are allowed. 輸入數字值。")
except KeyboardInterrupt:
print("
你已經按了Ctr C。")
exit(1)
if count == 3:
break: break.
我試圖解釋我在這個code中寫的東西。
正如你所提到的,一個用戶只能輸入三個無效的輸入,所以我增加了變數的計數,每次當用戶將輸入一個無效的輸入。但是如果一個用戶將輸入一個有效的輸入,那么計數將是0。這意味著用戶最多可以輸入三個無效的輸入。在輸入三個無效的輸入后,計數將是3,并且回圈中斷
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/331108.html
標籤:
