Python 模拟 Switch Case 语句:使用 if-elif-else 实现
在 Python 中,没有内置的 switch 语句。但可以通过使用 if-elif-else 语句来模拟 switch-case 语句的行为。
下面是一个示例:
def switch_case(argument):
switcher = {
1: 'Case 1',
2: 'Case 2',
3: 'Case 3'
}
return switcher.get(argument, 'Invalid case')
def main():
value = 2
result = switch_case(value)
print(result)
if __name__ == '__main__':
main()
在上面的示例中,switch_case 函数接受一个参数 argument,然后使用字典 switcher 来映射不同的 case 值到相应的结果。通过使用 switcher.get(argument, 'Invalid case'),我们可以获取到传入参数对应的结果,如果没有匹配的 case,则返回默认值 'Invalid case'。
在 main 函数中,我们调用 switch_case 函数并传入一个值为 2 的参数,然后将结果打印出来。输出结果将是 'Case 2',因为传入的参数是 2。
请注意,如果需要处理多个不同的情况,需要在 switcher 字典中添加相应的 case 和结果。
原文地址: https://www.cveoy.top/t/topic/bxuQ 著作权归作者所有。请勿转载和采集!