我的代碼塊中有很多例外陳述句,我需要將代碼縮短到 100 行。有沒有更好的方法用更少的行來撰寫下面的例外代碼之一?
while True:
try:
difficulty = int(input("Choose level 1: Easy 2: Difficult): "))
if (difficulty!=1 and difficulty!=2):
raise ValueError # this will send it to the print message
break
except ValueError:
print("Please enter the right value")
uj5u.com熱心網友回復:
更少的代碼行并不總是更好!
但是,您可以在這里改進一些事情。例如,對于您的示例中有限數量的有效輸入值,錯誤處理過于復雜:您檢查由于輸入不是數字而導致的例外,但您還要檢查該數字是否是兩個允許的數字之一。相反,您也可以只檢查輸入是否是兩個有效字串之一。如果是,您肯定知道可以毫無例外地完成到 int 的轉換,因此您不需要 try-catch 塊。
我能想出的最小代碼是相同功能的 5 行代碼:
response = None
while response not in ['1', '2']:
response = input("Choose level 1: Easy 2: Difficult): ")
if response not in ['1', '2']: print("Please enter the right value")
difficulty = int(response)
但是,優化可能在全域范圍內更有效(即,如果您進一步看,那么只有這段代碼)。例如,根據您要對變數執行的操作,可能根本不需要difficulty轉換為。int在這種情況下,您也可以洗掉最后一行。
但就像我之前說的,更少的行并不一定會讓代碼更好。為了可維護性,可讀性很重要。
uj5u.com熱心網友回復:
[...] 用更少的行來撰寫下面的例外代碼之一?
不完全是......但如果你愿意,你可以將它縮短一行:
while (difficulty!=1 and difficulty!=2):
這將使raiseandif陳述句變得無用。
uj5u.com熱心網友回復:
difficulty = int(input("Choose level (1: Easy 2: Difficult): "))
while (difficulty!=1 and difficulty!=2):
print("Please enter the right value")
difficulty = int(input("Choose level (1: Easy 2: Difficult): "))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/481343.html
下一篇:在多執行緒和行程程式中捕獲例外
