在 Python 中,没有内置的 switch 和 case 语句。但是,可以使用 if 语句来实现类似的功能。以下是一个示例:

def switch_case(argument):
    switch = {
        1: 'Case 1',
        2: 'Case 2',
        3: 'Case 3'
    }
    
    if argument in switch:
        return switch[argument]
    else:
        return 'Default case'

for i in range(1, 5):
    result = switch_case(i)
    print(result)

在上面的代码中,switch_case 函数模拟了一个 switch-case 语句。它使用一个字典来存储不同的情况和对应的处理逻辑。在 for 循环中,我们可以调用 switch_case 函数并传入不同的参数来模拟不同的情况。

输出结果为:

Case 1
Case 2
Case 3
Default case

在这个例子中,当参数为 1、2 或 3 时,函数会返回对应的情况。当参数不在字典中时,函数会返回默认的情况。这里使用 if 语句来判断参数是否在字典中,并返回对应的值。

Python 中使用 if 语句模拟 switch-case 语句

原文地址: https://www.cveoy.top/t/topic/bxq8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录