可以使用三目运算符替代if语句,或使用switch-case语句来实现。示例如下:
1.使用三目运算符:
def func(x):
return (x == 1 and 'one') or (x == 2 and 'two') or 'other'
print(func(1))
print(func(2))
print(func(3))
输出结果为:
one
two
other
2.使用switch-case语句:
def func(x):
return {
1: 'one',
2: 'two'
}.get(x, 'other')
print(func(1))
print(func(2))
print(func(3))
输出结果为:
one
two
other
两种方法都可以避免使用if语句,使代码更加简洁和易读。
下一篇:不使用if语句来调用多个类