如果通过一个或多个 if 语句,我如何执行相同的语句?

How can I perform the same statement if it passes one or more if statements?

如果它传递了一系列 if-elif 语句,我想执行相同的任务。

下面展示的是我正在努力实现的示例。该程序运行无错误,但我想知道是否有更简单的方法将 continue_program 分配给 Yes,而无需在满足其中一个条件的情况下多次输入。

word_form = "A string!"
continue_program = "No"

number = 2

if number == 1:
    word_form = "one"
    continue_program = "Yes"
elif number == 2:
    word_form = "two"
    continue_program = "Yes"
elif number == 3:
    word_form = "three"
    continue_program = "Yes"

您可以保留您的 if 块并在末尾检查“word_form”是否有长度,然后您可以将 coninue_program 分配给 True,例如:

word_form = ""
continue_program = False

number = 2

if number == 1:
    word_form = "one"
elif number == 2:
    word_form = "two"
elif number == 3:
    word_form = "three"

if len(word_form) > 0:
   continue_program = True

这可能有点简洁了:

d = {1: "one", 2: "two", 3: "three"}

continue_program = bool(word_form := d.get(number, "")))

d 中查找 number,这将导致所需的字符串或空字符串。作为副作用,将该字符串分配给 word_form。该字符串的布尔值进一步分配给 continue_program.

一些例子;首先,number == 6:

>>> bool(word_form := d.get(6, ""))
False
>>> word_form
''

现在,number == 1

>>> bool(word_form := d.get(1, ""))
True
>>> word_form
'one'

更新:使用条件表达式将 True/False 映射到 "Yes"/"No""

continue_program = "Yes" if (word_form := d.get(number, "")) else "No"

3.8 之前的版本,

word_form = d.get(number, "")
continue_program = "Yes" if word_form else "No"

在这里我可以想到两个使用 switch-case 类方法的解决方案:

1)

def num(arg):
switcher = {
    1:True,
    2:True,
    3:True,
    4:False
}
return switcher.get(arg, False)
def func1():
    print("hi func1")
def func2():
    print("hi func2")
def default():
    print("hi default")
def num2(arg):
    switcher = {
        1:func1,
        2:func2,
    }
    return switcher.get(arg, default)

num2(1)()
print("space")
num2(3)()

它将像这样打印:

hi func1
space
hi default

您可以从此处了解更多信息 switch-case