我想計算我的函式中有多少條 If/Else 陳述句。
我的代碼如下所示:
def countdown(type):
if type == 1:
//code
elif type == 2:
//code
else:
print(f"You have reached the end of the script. "
f"The maximum type of countdowns are: {x}")
exit(1)
在哪里x,應該有 if 查詢的數量(If/Else)。在這種情況下,有 3 個查詢。如果我在此函式中創建另一個 if/else 查詢,則不必更改腳本底部的警告。
這甚至可能嗎?
我正在使用 Python 3.10
uj5u.com熱心網友回復:
不要使用if..else,而是使用字典或串列:
types = {
1: ...,
2: ...
}
try:
types[type]
except KeyError:
print(f"You have reached the end of the script. "
f"The maximum type of countdowns are: {len(types)}")
exit(1)
究竟將什么放入 dict 作為值取決于......你能概括這個演算法,所以你只需要將一個值放入 dict 而不是實際代碼?偉大的。否則,將函式放入字典中:
types = {1: lambda: ..., 2: some_func, 3: self.some_method}
...
types[type]()
uj5u.com熱心網友回復:
由于您使用的是 Python 3.10,因此您可以使用 newmatch運算子。一個例子:
def countdown(type):
match type:
case 1:
# code
case 2:
# code
case _:
print(f"You have reached the end of the script. "
f"The maximum type of countdowns are: {x}")
exit(1)
對我來說,這是一個比一個更易讀的解決方案dict。
如何計算選項的數量,讓我們考慮一下我們有n不同且邏輯上分開的選項。在這種情況下,我建議您enum:
from enum import IntEnum
class CountdownOption(IntEnum):
FIRST = 1
SECOND = 2
# ...
# ...
def countdown(type):
match type:
case CountdownOption.FIRST:
# code
case CountdownOption.SECOND:
# code
case _:
print(f"You have reached the end of the script. "
f"The maximum type of countdowns are: {len(CountdownOption)}")
exit(1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/397588.html
標籤:Python if 语句 数数 python-3.10
上一篇:我猜將字串與整數進行比較的問題
